//请求url
let DOMAIN_BACK = "";
let API = '/api/';
const CONTENT_TYPE = 'application/json;charset=UTF-8';

//用于记录轮播框内容
var rotationList = [];
var programConfig = {};
//用于记录history
var historyRecord = [];
//每页显示的条数
let pageSize = 7;
//用户记录是否是轮播➕号点击
let flag = false;

// import from history.js
// const undoMgr = svgCanvas.undoMgr;
const ChangeElementCommand = svgedit.history.ChangeElementCommand;
var InsertElementCommand = svgedit.history.InsertElementCommand;
var RemoveElementCommand = svgedit.history.RemoveElementCommand;
const BatchCommand = svgedit.history.BatchCommand;

//用于初始化画布尺寸
function initCanvasSize() {
  //长宽比例
  let p1 = 0;
  //画布容器宽高度
  let containerW = $("#workarea").width();
  let containerH = $("#workarea").height();
  let p2 = WIDTH / HEIGHT;
  if (p2 > 1) {
    p1 = containerW / WIDTH - 0.05;//高度足够，根据宽度设置百分比
  } else {
    p1 = containerH / HEIGHT - 0.05;//高度足够，根据宽度设置百分比
  }
  // if(containerH < 1080*p1){ //高度不够，根据高度设置百分比
  //   p1 = containerH/1080 - 0.1;
  // }
  $("#zoom").val(p1 * 100).trigger("change");
}

//请求监听拦截
function requestListener(code, newToken) {
  if (code == 401 || code == 403) {
    const planObj = {
      planUpdate: false,
    }
    const obj = {
      state: planObj,
    };
    window.parent.postMessage(JSON.stringify({ data: obj }), "*");
    toProgramList();
    return;
  }
  const oldToken = localStorage.getItem("token");
  if (newToken != oldToken) {
    localStorage.setItem("token", newToken);//替换token
    const token = {
      refreshToken: newToken,
    };
    //更新父页面的token
    window.parent.postMessage(JSON.stringify({ data: token }), "*");
  }
}
//素材搜索按钮监听
function searchListener() {
  $(".material_panel .content .search-filed .search-btn").click(function () {
    let val = $(".material_panel .content .search-filed .search").val();
    let type = $(this).attr("type");
    requestList(type, val, 1);
  })
}

//初始化分页
function initPage(type, name, totalData) {
  let pageCount = Math.ceil(totalData / pageSize);
  $(".page").pagination({
    pageCount: pageCount,//总页数
    totalData: totalData, //数据总条数
    showData: pageSize, //每页显示的条数
    prevContent: '<',
    nextContent: '>',
    keepShowPN: true,
    jump: true,
    jumpBtn: 'TO',
    callback: function (index) {
      let html = '<span class="total">/' + pageCount + '</span>';
      $(".page .next").before(html);
      let pageNo = index.getCurrent();//页码
      requestList(type, name, pageNo);
    }
  });
  let html = '<span class="total">/' + pageCount + '</span>';
  $(".page .next").before(html);
  $(".material_panel .content .search-filed .search-btn").attr("type", type);
}

//初始化素材右侧选择列表
function requestList(type, name, pageNo) {
  $(".material_panel .content .loading").show();
  $(".material_panel .content .list_content ul").empty();
  $.ajax({
    type: "GET",
    url: DOMAIN_BACK + API + "resource/listPage",
    dataType: 'json',
    data: {
      pageNo: pageNo, //当前页码
      pageSize: pageSize, //分页大小
      type: type, //VIDEO视频  IMAGE图片
      name: name,//名称
    },
    beforeSend: function (request) {
      request.setRequestHeader("Authorization", localStorage.getItem("token"));
    },
    success: function (result, status, xhr) {
      const Authorization = xhr.getResponseHeader("authorization");
      requestListener(result.code, Authorization);
      if (result) {
        let datalist = result.data.list;
        length = result.data.totalCount;
        for (i in datalist) {
          let item = datalist[i];
          let temp = "";
          if (type == "VIDEO") {
            let extraInfo = JSON.parse(item.extraInfo);
            let duration = (parseInt(extraInfo.duration) / 1000).toFixed(1);
            temp = `<span>${(duration)}秒</span>`;
          }
          let html = `<li>
                    <img src=${(item.thumbUrl)} id=${(item.id)} original_url=${(item.url)} draggable="false">
                    <div class="mask">
                      <span class="name" title=${(item.filename)}>${(item.filename)}</span>
                      <span class="size" value=${(item.size)}>${(bytesToSize(parseInt(item.size)))}</span>
                      ${(temp)}
                    </div>
                  </li>`;
          if (type == "IMAGE") {
            $(".material_panel .content .list_content.img ul").append(html);
          } else if (type == "VIDEO") {
            $(".material_panel .content .list_content.video ul").append(html);
          }
        }
        if (pageNo == 1) {//初始化分页
          initPage(type, name, length);
        }
        let id = $("#material_field .content ul li .preview.active").attr("id");
        setItemSelected(id);
        $(".material_panel .content .loading").hide();
      } else {
        showModal(result.message);
      }
    },
    error: function (e) {
      $(".material_panel .content .loading").hide();
      if(e.responseJSON){
        var code = e.responseJSON.code;
        showModal(e.responseJSON.message);
        requestListener(code, "");
      }else{
        showModal("请求失败，请刷新重试");
      }
    }
  });
}

function conMenu(selected, tag) {
  //2.0.8 原生模式下不显示同步
  if (playModel != "android" && tag == "material") {
    $("#conMenu #syncTag").show();
  } else {
    $("#conMenu #syncTag").hide();
  }
  var elems = svgCanvas.getSelectedElems();
  var checkStatus = true;
  var preserveAspectRatio = false;
  var id = selected.getAttribute("id");
  if (elems.length == 1 && elems[0] && id == elems[0].getAttribute("id")) {
    var elem = elems[0];
      elems.map(elem => {
        if (elem.getAttribute("sync") == 'true') {
        } else {
          checkStatus = false;
        }
      });
      $("#conMenu #syncTag input").prop('checked', checkStatus);
    preserveAspectRatio = $(elem).find("image").attr("preserveAspectRatio");
    if (preserveAspectRatio) {
      preserveAspectRatio = true;
    }
    $("#conMenu #preserveAspectRatio input").prop('checked', preserveAspectRatio);
    $("#conMenu").css({ 'top': $("#selectorGrip_resize_nw").offset().top + 4, "left": $("#selectorGrip_resize_nw").offset().left + 4 }).show();

  } else if (elems.length == 0 && tag == "background") {
    preserveAspectRatio = $("#bgImage").attr("preserveAspectRatio");
    if (preserveAspectRatio) {
      preserveAspectRatio = true;
    }
    $("#conMenu #preserveAspectRatio input").prop('checked', preserveAspectRatio);
    $("#conMenu").css({ 'top': $("#bgImage").offset().top, "left": $("#bgImage").offset().left }).show();
    $("#conMenu #preserveAspectRatio").show();
  }
}

//初始化鼠标提示title
function setTooltip() {
  document.getElementById("svgroot").addEventListener("mouseover", function (e) {
    var obj = {
      background:'画布',
      textarea: '文本框',
      time:     '时间',
      weather:  '天气',
      material: '素材框',
      qrcode:   '二维码',
      barcode:  '条形码',
      webpage:  '网页',
      live:     '直播',
      shape:    '图形',
    };

    var selected = e.target;
    var tag = selected.getAttribute("tag");
    if (tag == null || tag == "") {
      tag = selected.parentNode.getAttribute("tag");
    }
    var title = obj[tag]?obj[tag]:obj['background'];
    $("#svgcontent title").html(title);
    // $("#conMenu").hide();
  });
}

// function setBlur(filters) {
//   $(filters).each(function () {
//     var elem_id = this.getAttribute("id").replace("_blur", "");
//     var width = this.getAttribute("width");
//     var height = this.getAttribute("height");
//     var val = $(this).find("fegaussianblur")[0].getAttribute("stddeviation");
//     var filter = svgCanvas.getElem(elem_id + '_blur');
//     var newblur = svgCanvas.addSvgElementFromJson({
//       "element": "feGaussianBlur",
//       "attr": {
//         "in": 'SourceGraphic',
//         "stdDeviation": val
//       }
//     });

//     filter = svgCanvas.addSvgElementFromJson({
//       "element": "filter",
//       "attr": {
//         "id": elem_id + '_blur'
//       }
//     });

//     filter.appendChild(newblur);
//     svgCanvas.findDefs().appendChild(filter);
//     if (width & height) {
//       svgCanvas.assignAttributes(filter, {
//         x: 0,
//         y: 0,
//         width: width,
//         height: height
//       });
//     }

//   })
// }

/**初始化画布以及轮播框【放在这里请求是为了避免editHtml内容过大导致localStorage装不下出现异常】**/
function initCanvas() {
  let id = window.methodDraw.id;
  $.ajax({
    type: "GET",
    url: DOMAIN_BACK + API + "program/getProgramDetail/" + id,
    dataType: 'json',
    beforeSend: function (request) {
      request.setRequestHeader("Authorization", localStorage.getItem("token"));
    },
    success: function (result, status, xhr) {
      const Authorization = xhr.getResponseHeader("authorization");
      requestListener(result.code, Authorization);
      if (result && result.data) {
        let data = JSON.parse(result.data.editHtml);
        let htmlStr = result.data.htmlStr;
        let content = $(htmlStr).find("#svgcontent>g")[1].innerHTML;//获取画布内容信息
        if ($(htmlStr).find("#svgcontent>defs").length > 0) {
          // let filters = $(htmlStr).find("#svgcontent>defs")[0].innerHTML;//存储模糊度
          // setBlur(filters);
        }
        $($("#svgcontent>g")[1]).empty().html(content);
        $("#svgcontent").attr({
          "width": $("#canvasBackground").attr("width"),
          "height": $("#canvasBackground").attr("height"),
          "x": $("#canvasBackground").attr("x"),
          "y": $("#canvasBackground").attr("y"),
        });
        rotationList = data;
        //2.0.8 原生情况下
        if(playModel == "android"){
          initLayout();
        }else{
          getRotation();
        }
        $("#material_field .content ul li .preview video").each(function () {
          if (!(navigator.userAgent.toLowerCase().indexOf("android") > 0)) {
            this.muted = true;
          }
          this.addEventListener('canplaythrough', function () {
            this.play();
          })
        });
        //初始化文本框内容
        for (i in rotationList) {
          let item = rotationList[i];
          if (item.tag == 'textarea') {
            let id = item.id;
            let temp = $(item.html);
            let obj = temp[0];//获取第一个文本框的内容
            let text = $(obj).find("foreignObject textarea").val();
            $("#svgcontent").find("#" + id + " textarea").val(text);
          }
        }
        //初始化时间控件
        if ($("foreignObject[tag='time'] .time").length > 0) { tick() }
        //2.0.8 如果是原生，默认选中svg_1
        if(playModel == "android"){
          $("#svg_1").mousedown();
        }
      } else {
        showModal(result.message);
      }
      $(".loading").hide();
    },
    error: function (e) {
      if(e.responseJSON){
        var code = e.responseJSON.code;
        showModal(e.responseJSON.message);
        requestListener(code, "");
      }else{
        showModal("请求失败，请刷新重试");
      }
    }
  });
}
//设置轮播内容
function setRotation() {
  console.log("setRotation")
  let selected = svgCanvas.getSelectedElems();
  let id = "";
  let tag = $(selected[0]).attr("tag");
  let sync = $(selected[0]).attr("sync");
  let preserveAspectRatio = $(selected).find("image,video").attr("preserveAspectRatio");
  let playList = [];
  let sizeList = [];
  if (selected[0] != undefined) {
    id = selected[0].id;
  } else {
    id = "bgImage";
    tag = "background";
    preserveAspectRatio = $("#bgImage").attr("preserveAspectRatio");
  }
  const html = $("#material_field .content ul")[0].innerHTML;
  let duration = 0;
  $("#material_field .content ul li .preview").each(function () {
    if ($(this).html() != "" && $(this).html() != null) {//记录轮播时长
      duration += parseInt($(this).parent().find(".num-input").val());
    }
    let id = $(this)[0].id;
    if (id != undefined && id != "" && id != null && !playList.includes(id)) {//记录轮播资源id
      playList.push(id);
    }
    let size = $(this).attr("size");
    if (size != undefined && size != "" && size != null) {//记录轮播资源id
      sizeList.push(size);
    }
  });
  
  const item = {
    id: id,
    tag: tag,
    html: html,
    duration: duration,
    playList: playList,
    sizeList: sizeList,
    sync: sync,//同步
    preserveAspectRatio: preserveAspectRatio,//按比例
  }
  if (rotationList.length > 0) {
    for (i in rotationList) {
      if (rotationList[i].id == id) {
        rotationList.splice(i, 1);
      }
    }
  }
  rotationList.push(item);
  setRotateIndex();
}
//初始化轮播列表
function getRotation() {
  console.log("getRotation")
  let selected = svgCanvas.getSelectedElems();
  let id = "";
  if (selected[0] != undefined) {
    id = selected[0].id;
  } else {
    id = "bgImage";
  }
  let html = `<li>
                <span class="del" style="display: none;">×</span>
                <div class="preview active"></div>
                <div class="mask"><span class="name" title=""></span></div>
                <div class="duration">
                  <span>时长</span>
                  <div class="number">
                    <input type="text" class="num-input" value="5">
                  </div>
                  <span>秒</span>
                </div>
              </li>`;
  if (rotationList.length > 0) {
    for (i in rotationList) {
      if (rotationList[i].id == id) {
        html = rotationList[i].html;
      }
    }
  }
  $("#material_field .content ul").empty().append(html);
  //初始化顺序角标
  $("#material_field .content ul li").each(function(){
    //初始化数字输入框
    var numberElement = $(this).find('.duration .number');
    var value = parseInt(numberElement.find(".num-input").val());
    numberElement.empty();
    initInputNumber(numberElement, value);

    var previewElement = $(this).find('.preview');
    // previewElement.attr('data-index',index+1);
    if (previewElement.hasClass("active")) {
      flag = false;
      previewElement.click();
    }
  });
  setRotateIndex();
  //初始化数字输入框
  // $("#material_field .content ul li .duration .number").each(function () {
  //   var value = parseInt($(this).find(".num-input").val());
  //   $(this).empty();
  //   initInputNumber($(this), value);
  // });
  // $("#material_field .content ul li .preview").each(function () {
  //   if ($(this).hasClass("active")) {
  //     flag = false;
  //     $(this).click();
  //     // $(this).parent().find("input").focus().blur();//用于编辑模式时初始化快捷键不好用处理
  //   }
  // });
}

function delRotation(id) {
  for(var i=0;i<rotationList.length;i++){
    if(rotationList[i].tag != "config" && rotationList[i].tag != "bgImage"){
      if(rotationList[i].id == id){
        rotationList.splice(i, 1);
      }
    }
  }
}
function insertAfter(newElement, targetElement) { // newElement是要追加的元素 targetElement 是指定元素的位置
  var parent = targetElement.parentNode; // 找到指定元素的父节点
  if (parent.lastChild == targetElement) { // 判断指定元素的是否是节点中的最后一个位置 如果是的话就直接使用appendChild方法
    parent.appendChild(newElement, targetElement);
  } else {
    parent.insertBefore(newElement, targetElement.nextSibling);
  };
};

function getLocation(canvas, x, y) {
  var bbox = canvas.getBoundingClientRect();
  var svgcontent = document.getElementById("svgcontent");
  var width = svgcontent.getAttribute("x");
  var height = svgcontent.getAttribute("y");
  return {
    x: Math.round(x - bbox.left - width), //x坐标显示值
    y: Math.round(y - bbox.top - height), //y坐标显示值
    cursor_x: Math.round(x - bbox.left - 16), //x参考线位置
    cursor_y: Math.round(y - bbox.top), //y参考线位置
  };
}
var isDown = false;
var x = 0;
var y = 0;
var l = 0;
var t = 0;
var moveObject = "";
//参考线方法
function referenceLine(svgCanvas) {
  var rulers = document.getElementsByClassName("ruler");
  var zoom = svgCanvas.getResolution().zoom;
  for (var i = 0; i < rulers.length; i++) {
    var ruler = rulers[i];
    var lines = document.createElement('div');
    lines.className = "lines";
    insertAfter(lines, ruler);
    ruler.addEventListener("mouseover", function () {
      var indicator = document.createElement('div');
      indicator.className = "indicator";
      var span = document.createElement('span');
      span.className = "value";
      indicator.appendChild(span);
      insertAfter(indicator, this.nextSibling);
    });
    ruler.addEventListener("mouseout", function () {
      var node = this.parentNode.getElementsByClassName("indicator")[0];
      this.parentNode.removeChild(node);
    });
    ruler.addEventListener("mousemove", function (e) {
      var node = this.parentNode.getElementsByClassName("indicator")[0];
      var span = node.getElementsByTagName("SPAN")[0];
      if (this.parentNode.className.indexOf("h-container") > -1) {
        span.innerHTML = Math.round(getLocation(this, e.clientX, e.clientY).x / zoom);
        node.style.left = getLocation(this, e.clientX, e.clientY).cursor_x + "px";
      } else {
        span.innerHTML = Math.round(getLocation(this, e.clientX, e.clientY).y / zoom);
        node.style.top = getLocation(this, e.clientX, e.clientY).cursor_y + "px";
      }
    });
    ruler.addEventListener("click", function (e) {
      var line = document.createElement('div');
      line.className = "line";
      var value = "";
      var val = $("#tools_left .reference_line select").val();
      var value_x = $('#tools_left .reference_line input[type="text"].custom.x').val();
      var value_y = $('#tools_left .reference_line input[type="text"].custom.y').val();
      if (this.parentNode.className.indexOf("h-container") > -1) {
        var left = getLocation(this, e.clientX, e.clientY).cursor_x;
        if (val == 1 && value_x != "") {
          value = value_x;
        } else {
          value = Math.round((getLocation(this, e.clientX, e.clientY).x) / zoom);
        }

        line.style.left = left + 'px';
        line.innerHTML = '<div class="action"><span class="del">×</span><span class="value">' + value + '</span></div>';
      } else {
        var top = getLocation(this, e.clientX, e.clientY).cursor_y;
        if (val == 1 && value_y != "") {
          value = value_y;
        } else {
          value = Math.round((getLocation(this, e.clientX, e.clientY).y) / zoom);
        }
        line.style.top = top + 'px';
        line.innerHTML = '<div class="action"><span class="del">×</span><span class="value">' + value + '</span></div>';
      }
      var lines = this.parentNode.getElementsByClassName("lines")[0];
      lines.appendChild(line);
      //del监听
      var dels = document.getElementsByClassName("del");
      for (var i = 0; i < dels.length; i++) {
        dels[i].onclick = function (ev) {
          var ev = ev || window.event;
          var target = ev.target || ev.srcElement;
          target.parentNode.parentNode.remove();
        }
      }
      //参考线移动监听
      line.onmousedown = function (e) {
        //获取x坐标和y坐标
        if (this.style.left != "" && this.style.left != null) {
          x = e.clientX;
          //获取左部和顶部的偏移量
          l = line.offsetLeft;
        } else {
          y = e.clientY;
          t = line.offsetTop;
        }
        //开关打开
        isDown = true;
        moveObject = this;
      };
      line.onmouseup = function () {
        //开关关闭
        isDown = false;
        moveObject = "";
      };
    });
  }
}

//鼠标移动
window.onmousemove = function (e) {
  var zoom = svgCanvas.getResolution().zoom;
  if (isDown == false) {
    return;
  }
  if (moveObject.style.left != "" && moveObject.style.left != null) {
    //获取x和y
    var nx = e.clientX;
    //计算移动后的左偏移量和顶部的偏移量
    var nl = nx - (x - l);
    var obj = $(".h-container > canvas")[0];
    moveObject.style.left = nl + 'px';
    var value = getLocation(obj, e.clientX, e.clientY).x;
  } else {
    var ny = e.clientY;
    var nt = ny - (y - t);
    var obj = $(".v-container > canvas")[0];
    moveObject.style.top = nt + 'px';
    var value = getLocation(obj, e.clientX, e.clientY).y;
  }
  //设置参考线显示坐标值
  $(moveObject).find(".value")[0].innerHTML = Math.round(value / zoom);
}

//控制右侧menu显示项目
function menuControl(tag) {
  console.log("menuControl:",tag);
  $("#material_field").show();
  switch (tag) {
    case 'background':
      $(".material_panel .tab .canvas").click();//默认选中第一个tab
      $("#canvas_panel h4").html("画布");
      break;

    case 'time':
      $("#textarea_panel h4").html("时间");
      tick();
      $(".context_panel").hide();
      $("#color_tools span").html("字体颜色");
      $("#background_tools span").html("背景颜色");
      //位置，旋转 透明度 模糊度，轮廓，字体颜色，背景色
      $("#textarea_panel,#selected_panel, #stroke_panel, #color_tools, #background_tools").show();
      //标题，字体样式，字体大小，行间距
      $("#textarea_panel h4,#tool_textarea_font_family,#tool_textarea_font_size,#tool_textarea_line_height").show(); //字体样式显示
      $("#material_field").hide();
      break;
    // case 'weather':
    //   $("#material_field").hide();

    case 'textarea':
      $("#textarea_panel h4").html("文本框");
      $(".context_panel").hide();
      $("#color_tools span").html("字体颜色");
      $("#background_tools span").html("背景颜色");
      //位置，旋转 透明度 模糊度，轮廓，字体颜色，背景色
      $("#textarea_panel,#selected_panel, #stroke_panel, #color_tools, #background_tools").show();
      //标题，字体样式，字体大小，行间距
      $("#textarea_panel h4,#tool_textarea_font_family,#tool_textarea_font_size,#tool_textarea_line_height").show(); //字体样式显示
      break;
    case 'material':
      $(".context_panel").hide();
      $(".list_content.canvas").hide();
      $("#canvas_panel").attr("style", "height:auto");
      $("#stroke_panel").show();
      $(".material_panel").show(); //素材选择tab
      $(".material_panel .tab .canvas").click();//默认选中第一个tab
      break;
    case 'qrcode':
    case 'barcode':
      $(".context_panel").hide();
      //位置，旋转 透明度 模糊度，轮廓，字体颜色，背景色，二维码/条形码
      $("#textarea_panel,#selected_panel,#stroke_panel,#color_tools, #background_tools,#code_panel").show();
      $("#textarea_panel h4,#tool_textarea_font_family,#tool_textarea_font_size,#tool_textarea_line_height").hide();//标题
      $("#code_panel h4").html((tag == 'qrcode') ? "二维码" : "条形码");
      $("#color_tools span").html("线条色");
      $("#background_tools span").html("填充色");
      $("#code_panel .button").attr("type", tag);
      break;
    case 'webpage':
      $(".context_panel").hide();
      //位置，旋转 透明度 模糊度，轮廓，字体颜色，背景色，网页
      $("#textarea_panel,#selected_panel,#stroke_panel,#webpage_panel").show();
      $("#textarea_panel h4,#tool_textarea_font_family,#tool_textarea_font_size,#tool_textarea_line_height").hide();
      break;
    case 'live':
      $(".context_panel").hide();
      //位置，旋转 透明度 模糊度，轮廓，字体颜色，背景色，网页
      $("#textarea_panel,#selected_panel,#stroke_panel,#live_panel").show();
      $("#textarea_panel h4,#tool_textarea_font_family,#tool_textarea_font_size,#tool_textarea_line_height").hide();
      break;
    case 'shape':
      //位置，旋转 透明度 模糊度，轮廓，字体颜色
      $("#color_tools").show();
      break;
    default:
      break;
  }
}
//设置foreignObject内部元素的样式
function setElementAttribute(tag, element) {
  console.log("setElementAttribute")
  switch (tag) {
    case 'time':
    case 'weather':
      inputTrigger(element);
    case 'textarea':
      var fontSize = element.getAttribute("font-size") + "px";
      var fontFamily = element.getAttribute("font-family");
      var lineHeight = element.getAttribute("line-height");
      var fill = element.getAttribute("fill");
      var color = fill == 'none' ? 'transparent' : fill;
      var fontWeight = element.getAttribute("font-weight");
      var fontStyle = element.getAttribute("font-style");
      var textDecoration = element.getAttribute("text-decoration");
      var strokeWidth = element.getAttribute("stroke-width");
      var background = element.getAttribute("background");
      element.children[0].style.fontSize = fontSize;
      element.children[0].style.fontFamily = fontFamily;
      element.children[0].style.lineHeight = lineHeight;
      element.children[0].style.color = color;
      element.children[0].style.fontWeight = fontWeight;
      element.children[0].style.fontStyle = fontStyle;
      element.children[0].style.textDecoration = textDecoration;
      element.children[0].style.webkitTextStrokeWidth = strokeWidth + 'px';
      element.children[0].style.background = background;
      break;
    default:
      break;
  }
}

function colorFormat(color) {
  var values = color
    .replace(/rgb?\(/, '')
    .replace(/\)/, '')
    .replace(/[\s+]/g, '')
    .split(',');
  var a = parseFloat(values[3] || 1),
    r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
    g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
    b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255);
  return ("0" + r.toString(16)).slice(-2) +
    ("0" + g.toString(16)).slice(-2) +
    ("0" + b.toString(16)).slice(-2);
}

function colorFormatReverse(color) {
  // 16进制颜色值的正则
  const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  // 把颜色值变成小写
  var color = color.toLowerCase();
  if (reg.test(color)) {
    // 如果只有三位的值，需变成六位，如：#fff => #ffffff
    if (color.length === 4) {
      let colorNew = "#";
      for (let i = 1; i < 4; i += 1) {
        colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
      }
      color = colorNew;
    }
    // 处理六位的颜色值，转为RGB
    let colorChange = [];
    for (var i = 1; i < 7; i += 2) {
      colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
    }
    // return "RGB(" + colorChange.join(",") + ")";
    return colorChange;
  } else {
    return color;
  }

}
//初始化左侧背景颜色和文字
function colorSelector(target) {
  console.log("colorSelector");
  var fill = target.getAttribute('fill');
  var color = fill == 'none' ? 'transparent' : fill;
  var bg = target.getAttribute('background');
  var background = bg == 'transparent' ? 'none' : bg;
  var p = { solidColor: fill, type: "solidColor" };
  var p1 = { solidColor: background, type: "solidColor" };
  var paint = new $.jGraduate.Paint(p);
  window.methodDraw.paintBox['fill'].setPaint(paint);
  $("#color_tools #fill_color rect").attr("fill", color);
  var paint1 = new $.jGraduate.Paint(p1);
  window.methodDraw.paintBox['background'].setPaint(paint1);
  $("#background_tools #background_color rect").attr("fill", background);
}
//初始化画布背景颜色
function canvasColorSelector(background) {
  console.log("canvasColorSelector");
  if (background.indexOf("rgb") > -1) {
    background = colorFormat(background);
  }
  var p = { solidColor: background, type: "solidColor" };
  var paint = new $.jGraduate.Paint(p);
  window.methodDraw.paintBox['canvas'].setPaint(paint);
  $("#canvas_color rect").attr("fill", background == "none" ? background : '#' + background);
}
//初始化左侧控制栏的值 位置轮廓
function initPosition(elem) {
  console.log("initPosition");
  let x = Math.round(elem.getAttribute("x")); //x轴位置
  let y = Math.round(elem.getAttribute("y")); //y轴位置
  let width = Math.round(elem.getAttribute("width")); //宽度
  let height = Math.round(elem.getAttribute("height")); //高度
  let stroke_width = elem.getAttribute("stroke-width");  //轮廓厚度
  var opacity = elem.getAttribute("opacity"); //透明度
  let blur = elem.getAttribute("blur"); //模糊度
  let angle = 0; //旋转
  let align = [
    elem.getAttribute("l"), elem.getAttribute("c"), elem.getAttribute("r"), elem.getAttribute("t"), elem.getAttribute("m"), elem.getAttribute("b")
  ]; //对齐
  $("#position_opts>div").removeClass("active");
  for (var i = 0; i < align.length; i++) {
    if (align[i] == "true") {
      $($("#position_opts>.draginput_cell")[i]).addClass("active");
    }
  }

  let st = window.getComputedStyle(elem, null);
  let transform = st.getPropertyValue("-webkit-transform") ||
    st.getPropertyValue("-moz-transform") ||
    st.getPropertyValue("-ms-transform") ||
    st.getPropertyValue("-o-transform") ||
    st.getPropertyValue("transform") || "FAIL";
  if (transform != "none" && transform != "FAIL") {
    var values = transform.split('(')[1].split(')')[0].split(',');
    var a = values[0];
    var b = values[1];
    angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));
  }
  var moveAble = elem.getAttribute("moveable");
  elementMoveAble(moveAble)?
  $('#textarea_panel #textarea_x,#textarea_panel #textarea_y').css("pointer-events","auto"):
  $('#textarea_panel #textarea_x,#textarea_panel #textarea_y').css("pointer-events","none");
  $('#textarea_panel #textarea_x').val(x);
  $('#textarea_panel #textarea_y').val(y);
  var resizeAble = elem.getAttribute("resizeable");
  elementResizeAble(resizeAble)?
  $('#textarea_panel #textarea_width,#textarea_panel #textarea_height').css("pointer-events","auto"):
  $('#textarea_panel #textarea_width,#textarea_panel #textarea_height').css("pointer-events","none");
  $('#textarea_panel #textarea_width').val(width);
  $('#textarea_panel #textarea_height').val(height);
  $('#group_opacity').val(opacity == null ? 100 : opacity * 100);
  $("#tool_angle #angle").val(angle);
  $("#tool_blur #blur").val(blur == null ? 0 : blur);
  $('#stroke_width').val(stroke_width);
}
//初始化右侧控制栏的值
function UpdateTextareaPanel(elem, tag) {
  let font_size = elem.getAttribute("font-size");
  let font_family = elem.getAttribute("font-family");
  let select = document.getElementById("textarea_font_family_dropdown");
  let line_height = elem.getAttribute("line-height");
  // let stroke_width = elem.getAttribute("stroke-width");
  select.selectedIndex = 3;
  // $('#textarea_panel').css("display", "inline");
  $('#textarea_panel').show();
  $('#tool_textarea_italic').toggleClass('active', svgCanvas.getItalic());
  $('#tool_textarea_bold').toggleClass('active', svgCanvas.getBold());
  $('#tool_textarea_underline').toggleClass('active', svgCanvas.getUnderline());
  $('#textarea_font_family').val(font_family);
  $('#textarea_font_size').val(font_size);
  $('#textarea_line_height').val(line_height);
  $('#textarea').val(elem.textContent);
  $('#textarea_preview_font').text(font_family.split(",")[0].replace(/'/g, "")).css('font-family', font_family);
  // $('#stroke_width').val(stroke_width);

  // if (svgCanvas.addedNew) {
  // Timeout needed for IE9
  // setTimeout(function() {
  // $('#textarea').focus().select();
  // },100);
  // }
  initPosition(elem);
  colorSelector(elem);
  menuControl(tag);
}

//获取元素在父元素中的index
function _index(el) {
  var index = 0;
  if (!el || !el.parentNode) {
    return -1;
  }
  while (el && (el = el.previousElementSibling)) {
    index++;
  }
  return index;
}

var draging = null;

document.addEventListener("dragstart", function (event) {
  //firefox设置了setData后元素才能拖动！！！！
  event.dataTransfer.setData("te", event.target.innerText); //不能使用text，firefox会打开新tab
  //event.dataTransfer.setData("self", event.target);
  draging = event.target;
});
document.addEventListener("dragover", function (event) {
  event.preventDefault();
  var target = event.target.parentNode;
  //因为dragover会发生在ul上，所以要判断是不是li
  if (target.nodeName === "LI" && target !== draging) {
    // if(target.parent.nodeName === "LI" && target !== draging){
    if (_index(draging) < _index(target)) {
      target.parentNode.insertBefore(draging, target.nextSibling);
    } else {
      target.parentNode.insertBefore(draging, target);
    }
  }
});

//初始化二维码和条形码输入框
function initCodeInput() {
  var value = $("#material_field .content ul li .preview.active img").attr("value");
  if (value != undefined) {
    $("#code_panel input[type='text']").val(value);
  } else {
    $("#code_panel input[type='text']").val("");
  }
}
//初始化数字输入框
function initInputNumber(items, defaultValue, max) {
  items.numInput({
    width: '65px',//宽度
    height: '22px',
    positive: true,//允许输入正数
    negative: false,//允许输入负数
    //faq：positive，negative不能同时false，同时false按同时为true处理
    floatCount: 0,//小数点后保留位数
    //命名空间，防止样式冲突
    wrapperClass: 'num-input-wrap',//最外层容器
    inputClass: 'num-input',//input输入框
    addClass: 'add',//增加按钮
    subtractClass: 'subtract',//减少按钮
    defaultValue: defaultValue == undefined ? 5 : defaultValue,
    interval: 1,//增加&减少按钮每次变化的值
    max: max
  });
}

//根据输入框变化更新轮播内容
function inputTrigger(elem) {
  setTimeout(function () {
    let tag = elem.getAttribute("tag");
    if (tag != null && tag != "") {
      let html = elem.outerHTML;
      let width = 0;
      let height = 0;
      if (tag != "shape") { //图形
        width = $(elem)[0].width.animVal.value;
        height = $(elem)[0].height.animVal.value;
      } else {
        width = elem.getBoundingClientRect().width;
        height = elem.getBoundingClientRect().height;
      }
      let angle = 0; //旋转
      let st = window.getComputedStyle(elem, null);
      let transform = st.getPropertyValue("-webkit-transform") ||
        st.getPropertyValue("-moz-transform") ||
        st.getPropertyValue("-ms-transform") ||
        st.getPropertyValue("-o-transform") ||
        st.getPropertyValue("transform") || "FAIL";
      if (transform != "none" && transform != "FAIL") {
        let values = transform.split('(')[1].split(')')[0].split(',');
        let a = values[0];
        let b = values[1];
        angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));
      }
      let currentRotateElement = $("#material_field .content ul li .preview.active");
      switch (tag) {
        case 'textarea':
          let value = $(elem).find("textarea").val();
          let textarea = elem.children[0];
          let color = elem.getAttribute("fill");
          textarea.style.color = color;
          currentRotateElement.empty().append('<svg viewBox="0 0 ' + width + ' ' + height + '">' + html + '</svg>').attr("tag",tag);
          currentRotateElement.find("svg").css("transform", "rotate(" + angle + "deg)");
          currentRotateElement.find("svg textarea").html(value);
          break;
        case 'material':
        case 'qrcode':
        case 'barcode':
          $(elem).find("svg").attr("viewBox", ["0 0 " + width + " " + height]);
          $(elem).find("image").attr({ "width": width, "height": height });
        case 'webpage':
        case 'live':
          // var index = 0;
          $("#material_field .content ul li .preview").each(function (i) {
            if ($(this).hasClass("active")) {
              index = i;
            }
          });
          currentRotateElement.find("svg").attr("viewBox", "0 0 " + width + " " + height + "").css("transform", "rotate(" + angle + "deg)");
          currentRotateElement.find("foreignObject").attr({
            "width": width,
            "height": height,
            "opacity": elem.getAttribute("opacity") == null ? 1 : elem.getAttribute("opacity"),
            "blur": elem.getAttribute("blur") == null ? 0 : elem.getAttribute("blur"),
            // "filter": 'url(#' + elem.id + '_' + index + '_blur)',
            "orginal-transform": elem.getAttribute("transform"),
          });
          if(tag == 'live'){
            let x = $(elem).find("image").attr('x');
            let y = $(elem).find("image").attr('y');
            currentRotateElement.find('img').css('transform',`translate(${x}px, ${y}px)`);
          }
          break;
        case 'time':
          // case 'weather':
          // let head = $($(elem).find("iframe")[0].contentDocument).find("head"); //画布中iframe
          // let style = $(elem).find("iframe")[0].attributes["style"].value;
          // $(head).find("style").remove();
          // $(head).append(`<style type="text/css">div{${(style)}}</style>`); //画布中设置样式
          // if(currentRotateElement.find("foreignObject").length == 0){
          //   currentRotateElement.append('<svg viewBox="0 0 '+width+' '+height+'">' + html + '</svg>');
          // }else{
          //   currentRotateElement.find("foreignObject").attr({
          //     "width":width,
          //     "height":height,
          //     "opacity":elem.getAttribute("opacity") == null ? 1 : elem.getAttribute("opacity"),
          //     "blur":elem.getAttribute("blur") == null ? 0 : elem.getAttribute("blur"),
          //     "filter": 'url(#' + elem.id + '_blur)',
          //     "orginal-transform":elem.getAttribute("transform"),
          //   });
          // }
          // setTimeout(function(){
          //   $(currentRotateElement.find("iframe")[0].contentDocument).find("head style").remove()
          //   $(currentRotateElement.find("iframe")[0].contentDocument).find("head").append(`<style type="text/css">div{${(style)}}</style>`);//轮播框中iframe设置样式 
          // },100);
          // currentRotateElement.find("svg").css("transform","rotate("+angle+"deg)");
          break;
        case "shape":
          let x = parseInt($("#path_x").val());
          let y = parseInt($("#path_y").val());
          let p = Math.floor($("#material_field .content ul li .preview.active svg").width() / width * 100) / 100;
          currentRotateElement.empty().append('<svg viewBox="0 0 ' + (width) + ' ' + (height) + '">' + html + '</svg>');
          currentRotateElement.find("svg path").attr("transform", "scale(" + p + ") translate(" + (0 - x) + "," + (0 - y) + ")");
          currentRotateElement.find("svg").css("transform", "rotate(" + angle + "deg)");
          break;
        default:
          break
      }
      setRotation();
    }
  }, 200);

}

//控制图形弹出框显示或隐藏
// function shapeListener(){
//   $("#tools_shapelib_show").on('click',function(){
//     $("#tools_shapelib").is(":hidden") ? $("#tools_shapelib").fadeIn() : $("#tools_shapelib").fadeOut();
//   });
// }

//通过监听文本框输入的值更新轮播框内容
function textAreaInputListener() {
  $(document).on('input', "foreignObject[tag='textarea'] textarea", function (e) {
    let elem = e.target.parentNode;
    inputTrigger(elem);
  })
}

function setRotateIndex(){
  $("#material_field .content ul li .preview").each(function(index){
    $(this).attr('data-index',index+1);
  });
}
//元素切换控制样式列表值
function initMenuListener() {
  $("#svgcanvas").on('mousedown', function (e) {
    if(e.button == 1 || e.button == 2) return;//鼠标中间键和右键返回
    console.log("windows mousedown");
    $("#conMenu").hide();
    if (svgCanvas.getSelectedElems().length > 1) {//多选
      $("#tools_top").addClass('multies');
    } else {
      $("#tools_top").removeClass('multies');
    }
    getRotation();
    let target = e.target;
    let element = target.parentNode;
    let tag = element.getAttribute("tag");
    if (target.id == "svgroot") {
      tag = "background";
    } else if (tag != "textarea") {
      tag = target.getAttribute("tag");
    }
    switch (tag) {
      case 'background':
        menuControl("background");
        conMenu(target, tag);
        break;
      // case 'textarea': //文本框
        //haoyan 调整大小和切换选中时控制textarea样式
        // let tag1 = element.getAttribute("tag");
        // setElementAttribute(tag1, element);
        // UpdateTextareaPanel(element, tag1);
        // break;
      // case 'time':  //时间
      // case 'weather': //天气
      //   setElementAttribute(tag, target);
      //   UpdateTextareaPanel(target, tag);
      //   break;
      case 'qrcode': //二维码
      case 'barcode': //条形码
        initCodeInput();
      case 'material': //素材框
        conMenu(target, tag);
        menuControl(tag);
        initPosition(target);
        break;
      case 'live': //直播
        menuControl(tag);
        initPosition(target);
        var src = $("#material_field .content ul li .preview.active img").attr("unique");
        $("#live_panel input[type='text']").val(src);
        break;
      case 'webpage': //网页
        var src = $(target).find("iframe").attr("src");
        $("#webpage_panel input[type='text']").val(src);
        menuControl(tag);
        break;
      default:
        break;
    }

  });
}

//监听参考线下拉框
function lineSelectListener() {
  $("#tools_left .reference_line select").change(function () {
    let val = $(this).val();
    if (val == 0) {//平均参考线
      $("#tools_left .reference_line .number").show();
      $("#tools_left .reference_line .custom").hide();
    } else {//自定义参考线
      $("#tools_left .reference_line .number").hide();
      $("#tools_left .reference_line .custom").show();
    }
  })
}

//新建参考线按钮点击
function addLineListener() {
  $("#tools_left .button").click(function () {
    //清空参考线
    $(".line").remove();
    //参考线数量
    let x = 0;
    let y = 0;
    //画布宽高
    let canvasW = $("#canvasBackground")[0].width.animVal.value;
    let canvasH = $("#canvasBackground")[0].height.animVal.value;
    let val = $("#tools_left .reference_line select").val();
    if (val == 0) {//平均参考线
      x = parseInt($("#tools_left .x input[type='text']").val());
      y = parseInt($("#tools_left .y input[type='text']").val());
      //画布/参考线数量 = 参考线相对于画布位置
      let averageX = canvasW / (x + 1);
      let averageY = canvasH / (y + 1);
      if (x > 0) {
        for (var i = 1; i <= x; i++) {
          let valuex = parseInt($("#canvasBackground").offset().left) + i * averageX;
          let valuey = parseInt($("#canvasBackground").offset().top);
          let target = $("#ruler_x canvas")[0];
          let eventObj = document.createEvent('MouseEvents');
          eventObj.initMouseEvent('click', true, true, window, 1, 0, 0, valuex, valuey, false, false, true, false, 0, null);
          target.dispatchEvent(eventObj);
        }
      }
      if (y > 0) {
        for (var j = 1; j <= y; j++) {
          let valuex = parseInt($("#canvasBackground").offset().left);
          let valuey = parseInt($("#canvasBackground").offset().top) + j * averageY;
          let target = $("#ruler_y canvas")[0];
          let eventObj = document.createEvent('MouseEvents');
          eventObj.initMouseEvent('click', true, true, window, 1, 0, 0, valuex, valuey, false, false, true, false, 0, null);
          target.dispatchEvent(eventObj);
        }
      }
    } else {//自定义参考线
      let zoom = svgCanvas.getResolution().zoom;
      x = Math.round(parseInt($('#tools_left .reference_line input[type="text"].custom.x').val()) * zoom);
      y = Math.round(parseInt($('#tools_left .reference_line input[type="text"].custom.y').val()) * zoom);
      if (!isNaN(x)) {
        var bbox = $("#ruler_x canvas")[0].getBoundingClientRect();
        var svgcontent = document.getElementById("svgcontent");
        var width = parseInt(svgcontent.getAttribute("x"));
        let valuex = parseInt(bbox.left) + width + x;
        let valuey = parseInt($("#canvasBackground").offset().top);
        let target = $("#ruler_x canvas")[0];
        let eventObj = document.createEvent('MouseEvents');
        eventObj.initMouseEvent('click', true, true, window, 1, 0, 0, valuex, valuey, false, false, true, false, 0, null);
        target.dispatchEvent(eventObj);
      }
      if (!isNaN(y)) {
        var bbox = $("#ruler_y canvas")[0].getBoundingClientRect();
        var svgcontent = document.getElementById("svgcontent");
        var height = parseInt(svgcontent.getAttribute("y"));
        var valuey = parseInt(bbox.top) + height + y;
        let valuex = parseInt($("#canvasBackground").offset().left);
        let target = $("#ruler_y canvas")[0];
        let eventObj = document.createEvent('MouseEvents');
        eventObj.initMouseEvent('click', true, true, window, 1, 0, 0, valuex, valuey, false, false, true, false, 0, null);
        target.dispatchEvent(eventObj);
      }
    }
  });
}

//样式或素材选择区域tab选择
function tabListener() {
  $(".material_panel .tab label").click(function (e) {
    var target = $(e.target);
    var selected = svgCanvas.getSelectedElems();
    $(".material_panel .tab label").removeClass("active");
    var className = target[0].className;
    let type = "";
    target.addClass("active");
    $(".material_panel .content .list_content").hide();
    $(".material_panel .content .list_content." + className + "").show();
    if (className == "canvas") {//样式tab
      $(".page").empty().hide();
      $(".material_panel .content .search").hide();
      $("#stroke_panel,#textarea_panel").show(); ////旋转,对齐,轮廓,位置
      $("#textarea_panel h4,#tool_textarea_font_family,#tool_textarea_font_size,#tool_textarea_line_height").hide(); //字体样式不显示
       //2.0.8 控制layout右侧菜单旋转，透明度，对齐不可见
       var element = svgCanvas.getSelectedElems()[0];
       if(element){//针对素材框
        var isLayout = element.getAttribute('type');
        if(isLayout == 'layout'){
          var id = element.getAttribute('id');
          var index = id.replace('svg_','');
          $("#canvas_panel h4").html("画布"+index);
          $("#selected_panel").hide();//旋转,对齐,轮廓
        }else{
          $("#canvas_panel h4").html("素材框");
          $("#selected_panel").show(); //旋转,对齐,轮廓
        }
       }
       
    } else {
      $(".material_panel .content .search").show();
      $("#selected_panel,#stroke_panel,#textarea_panel").hide();
      if (className == "img") {
        type = "IMAGE";
      } else if (className == "video") {
        type = "VIDEO";
      }
      requestList(type, "", 1);//资源列表数据请求
    }
    if (selected != "" && selected != null) { //素材框
      $(".list_content.canvas").hide();
    } else { //画布
      $("#selected_panel,#stroke_panel,#textarea_panel").hide();
      // $(".context_panel").hide();
      // $(".list_content.canvas").show();
    }
  });
}

//图片或视频点击事件，向素材框添加元素
function materialChooseListener() {
  $(".material_panel .content .list_content ul").on('click', 'li', function () {
    console.log("素材点击")
    $(".material_panel .content .list_content ul li img").removeClass("active");
    let item = $(this).find("img");
    item.addClass("active");
    let parent = $(this).parents('.list_content');
    let html = "";
    let id = item.attr("id");
    let size = $(this).find(".size").attr("value");
    let name = $(this).find(".name").attr("title");
    let src = item.attr("original_url");
    let selected = svgCanvas.getSelectedElems();
    let elem = "";
    let width = 0;
    let height = 0;
    let fill = "";
    let tag = "";
    let durant = 5;
    let preserveAspectRatio = "";
    if (selected != "" && selected != null) {
      let tag = selected[0].getAttribute("tag");
      let img = $(selected[0]).find("image");
      if (tag == "material") {
        width = $(selected)[0].width.animVal.value;
        height = $(selected)[0].height.animVal.value;
        elem = img[0];
      }
      preserveAspectRatio = img.attr("preserveAspectRatio");
    } else {
      //设置背景图片
      elem = $("#bgImage")[0];
      width = elem.width.animVal.value;
      height = elem.height.animVal.value;
      fill = $("#canvas_background").attr("fill");//背景颜色
      preserveAspectRatio = $("bgImage").attr("preserveAspectRatio");
    }
    let obj = $("#material_field .content ul li .preview.active svg");
    let transform = "";
    let orginal_transform = "";
    let opacity = 1;
    let blur = 0;
    // let filter = "";
    if (obj.length > 0) {
      var element = obj.find("foreignObject");
      transform = obj[0].style.transform;
      orginal_transform = element.attr("orginal-transform");
      opacity = element.attr("opacity") == null ? 1 : element.attr("opacity");
      blur = element.attr("blur") == null ? 0 : element.attr("blur");
      // filter = element.attr("filter");
    }

    if ($(parent[0]).hasClass('img')) {
      tag = "img";
      html = `<svg viewBox="0 0 ${(width)} ${(height)}" style="transform:${(transform)}">
                <foreignObject width="${(width)}" height="${(height)}" 
                  opacity="${(opacity)}" blur="${(blur)}" 
                  orginal-transform="${(orginal_transform)}">
                  <image src="${(src)}" style="background:${(fill)}" unique=${(id)} preserveAspectRatio="${preserveAspectRatio}"/>
                </foreignObject>
              </svg>`;
    } else if ($(parent[0]).hasClass("video")) {
      tag = "video";
      let url = item.attr("src")
      html = `<svg viewBox="0 0 ${(width)} ${(height)}" style="transform:${(transform)}">
                <foreignObject width="${(width)}" height="${(height)}"
                  opacity="${(opacity)}" blur="${(blur)}" 
                  orginal-transform="${(orginal_transform)}">
                    <video width="100%" height="100%"  loop="" src="${(src)}" unique=${(id)} poster=${(url)}
                      original_url="${(url)}" style="background:${(fill)}" preserveAspectRatio="${preserveAspectRatio}">
                    </video>
                </foreignObject>
              </svg>`;
      src = url;
      durant = Math.round($(this).find("span:last").html().split('秒')[0]);
    }
    $("#material_field .content ul li .preview.active").parent().find('.number').empty();
    initInputNumber($("#material_field .content ul li .preview.active").parent().find(".number"), durant);
    const index = $("#material_field .content ul li .preview.active").parent().index();
    //记录初始化时轮播框内容
    if (historyRecord.length == 0) {
      historyRecord.push({
        "cursor": 0,
        "index": index,//记录第几个轮播框
        "id": $("#material_field .content ul li .preview.active")[0].id,
        "html": $("#material_field .content ul li .preview.active")[0].outerHTML,
      });
    }

    $("#material_field .content ul li .preview.active").attr({ "id": id, "tag": tag, "size": size }).html(html);
    if($("#material_field .content ul li .preview.active").next().hasClass("mask")){
      $("#material_field .content ul li .preview.active").next().find(".name").attr("title",name).html(name);
    }else{
      $("#material_field .content ul li .preview.active").after(`<div class="mask"><span class="name" title=${name}>${name}</span></div>`)
    }
    $("#material_field .content ul li .preview.active video").each(function () {
      this.addEventListener('canplaythrough', function () {
        this.play();
      });
    });
    if (null === $(this).click.caller) {//用户点击调用
      //向操作历史列表中添加操作记录
      let batchCmd = new BatchCommand("Change image");
      let changes = {
        'xlink:href': elem.getAttribute('xlink:href'),
        'unique': elem.getAttribute('unique'),
      };

      elem.setAttribute("unique", id);
      svgCanvas.setHref(elem, src);

      //向操作历史列表中添加操作记录
      batchCmd.addSubCommand(new ChangeElementCommand(elem, changes, index.toString()));
      svgCanvas.undoMgr.addCommandToHistory(batchCmd);

      let flag = true;
      for (i in historyRecord) {
        if (historyRecord[i].index == index && historyRecord[i].id == id) {
          flag = false;
        }
      }
      if (flag) {
        historyRecord.push({
          "cursor": svgCanvas.undoMgr.undoStackPointer,
          "index": index,//记录第几个轮播框
          "id": id,
          "html": $("#material_field .content ul li .preview.active")[0].outerHTML,
        });
      }
    }
    setRotation();
  });
}

//素材选择框显示隐藏
function rotationFieldListener() {
  $("#material_field .title span").click(function () {
    if ($(this).hasClass("cart-down")) {
      $("#material_field").addClass("hide");
      $(this).removeClass("cart-down").addClass("cart-up");
    } else {
      $("#material_field").removeClass("hide");
      $(this).removeClass("cart-up").addClass("cart-down");
    }
  });
}

//根据选择轮播框初始化资源列表选择状态
function setItemSelected(id) {
  $(".material_panel .content .list_content ul li").each(function (i) {
    var img = $(this).find("img");
    var index = img[0].id;
    if (index == id) {
      img.addClass("active");
    }
  });
}
//根据素材选择框选中状态，初始化组件的状态
function rotationFieldSelectListener() {
  $("#material_field .content ul").on('click', "li>.preview", function (e) {
    // console.log("切换")
    $(".material_panel .content .list_content ul li img").removeClass("active");
    var target = $(e.target);
    var id = target.attr('id');
    if (target.hasClass("preview")) {
      $("#material_field .content ul li>.preview").removeClass("active");
      target.addClass("active");
      var src = "";
      let unique = "";
      var selected = svgCanvas.getSelectedElems();
      var elem = "";
      var tag = "";
      var transform = "";
      var opacity = 1;
      var blur = 0;
      // var filter = "";
      if (selected[0] == undefined) {
        tag = "background";
      } else {
        tag = selected[0].getAttribute("tag");
      }
      switch (tag) {
        case 'background':
          //设置背景图片
          elem = $("#bgImage")[0];
          //设置背景颜色
          var obj = target.find("foreignObject");
          let color = '262732';
          if (obj.length > 0) {
            let background = obj.children()[0].style.background;
            if (background != "" && background != null) {
              color = background;
            }
            var preserveAspectRatio = $(obj).find("img,video").attr("preserveaspectratio");
            if (preserveAspectRatio == "none") {
              elem.setAttribute("preserveAspectRatio", preserveAspectRatio);
            } else {
              elem.removeAttribute("preserveAspectRatio");
            }
          }
          canvasColorSelector(color);
          break;
        case 'textarea':
          if (e.originalEvent != undefined || flag) { //切换
            var fill = "#000000";
            var fontFamily = playModel=='android'?'sans':'Helvetica, Arial, sans-serif';
            var fontSize = "24";
            var background = "transparent";
            var fontWeight = "";
            var fontStyle = "";
            var textDecoration = "";
            var text = "";
            var lineHeight = "1.2"
            if (target.find("foreignObject").length != 0) {
              var obj = target.find("foreignObject");
              text = obj.find("textarea").val();
              fill = obj.attr("fill");
              fontFamily = obj.attr("font-family");
              fontSize = obj.attr("font-size");
              background = obj.attr("background");
              fontWeight = obj.attr("font-weight");
              fontStyle = obj.attr("font-style");
              textDecoration = obj.attr("text-decoration");
              transform = obj.attr("transform") == undefined ? "" : obj.attr("transform");
              opacity = obj.attr("opacity") == undefined ? 1 : obj.attr("opacity");
              blur = obj.attr("blur") == undefined ? 0 : obj.attr("blur");
              lineHeight = obj.attr("line-height");
              // filter = obj.attr("filter");
            }
            $(selected[0]).attr({
              "fill": fill,
              "font-family": fontFamily,
              "font-size": fontSize,
              "background": background,
              "font-weight": fontWeight,
              "font-style": fontStyle,
              "text-decoration": textDecoration,
              "transform": transform,
              "opacity": opacity,
              "blur": blur,
              "line-height":lineHeight,
            });
            // if (filter) {
            //   $(selected[0]).attr({ "filter": filter });
            // } else {
            //   $(selected[0]).removeAttr("filter");
            // }
            var textarea = $(selected[0]).find("textarea");
            textarea.css({ "font-size": fontSize + 'px', "font-family": fontFamily, "color": fill, "background": background }).val(text);
            //触发输入框元素点击事件，初始化右侧状态栏
            setTimeout(function () {
              $(selected[0]).find("textarea").click().focus();
              //光标移动到输入框最后
              textarea[0].setSelectionRange(textarea[0].value.length, textarea[0].value.length);
              setElementAttribute(tag, selected[0]);
              UpdateTextareaPanel(selected[0], tag);
              //设置旋转角度
              var angle = $("#angle").val();
              svgCanvas.setRotationAngle(parseInt(angle), true);
              //设置模糊度
              // svgCanvas.setBlur(blur);
            }, 20);
          }
          setRotation();
          break;
        case 'webpage':
          if (e.originalEvent != undefined || flag) { //切换
            $("#webpage_panel .error").hide();
            const iframe = target.find("iframe");
            if(iframe.length == 0) return;
            const src = iframe[0].src;
            if (src) {
              $(selected[0]).find("iframe")[0].src = src;
            } else {
              const iframe1 = iframe[0].outerHTML;
              $(selected[0]).find("iframe").remove();
              $(selected[0]).append(iframe1);
            }

            if (target.find("foreignObject").length > 0) {
              var obj = target.find("foreignObject");
              transform = obj.attr("orginal-transform");
              if (transform && transform != "null") {
                $(selected[0]).attr("transform", transform);
              } else {
                $(selected[0]).removeAttr("transform");
              }
              opacity = obj.attr("opacity") == undefined ? 1 : obj.attr("opacity");
              blur = obj.attr("blur") == undefined ? 0 : obj.attr("blur");
              // filter = obj.attr("filter");
              $(selected[0]).attr({
                "opacity": opacity,
                "blur": blur,
              });
              // if (filter) {
              //   $(selected[0]).attr({ "filter": filter });
              // } else {
              //   $(selected[0]).removeAttr("filter");
              // }
            }
            $("#webpage_panel input[type='text']").val(src);
            initPosition(selected[0]);
            // //设置旋转角度
            var angle = $("#angle").val();
            svgCanvas.setRotationAngle(parseInt(angle), true);
            setRotation();
          }
          break;
          case 'live':
            if (e.originalEvent != undefined || flag) { //切换
              $("#live_panel .error").hide();
              var img = target.find('img');
              if(img.length == 0){
                $("#live_panel input[type='text']").val("");
                return;
              };
              var src = img.attr('unique');//直播流路径
              if(src){
                $("#live_panel input[type='text']").val(src);
              }
            }
            break;
        case 'qrcode':
        case 'barcode':
          initCodeInput();
        case 'material':
          if (e.originalEvent != undefined || flag) { //切换
            if (target.find("foreignObject").length > 0) {
              var obj = target.find("foreignObject");
              transform = obj.attr("orginal-transform");
              if (transform && transform != "null") {
                $(selected[0]).attr("transform", transform);
              } else {
                $(selected[0]).removeAttr("transform");
              }
              opacity = obj.attr("opacity") == undefined ? 1 : obj.attr("opacity");
              blur = obj.attr("blur") == undefined ? 0 : obj.attr("blur");
              // filter = obj.attr("filter");
            }
            $(selected[0]).attr({
              // "transform":transform,
              "opacity": opacity,
              "blur": blur,
            });
            // if (filter) {
            //   $(selected[0]).attr({ "filter": filter });
            // } else {
            //   $(selected[0]).removeAttr("filter");
            // }

            elem = $(selected[0]).find("image")[0];
            setTimeout(function () {
              initPosition(selected[0]);
              // 设置旋转角度
              var angle = $("#angle").val();
              svgCanvas.setRotationAngle(parseInt(angle), true);
              // 设置模糊度
              // svgCanvas.setBlur(blur);
            }, 20);
          }
          break;
        // case 'time':
        //   setRotation();
        //   break;
        default:
          break;
      }
      //判断图片还是视频，更新元素图片
      if (target.attr("tag") == "img" || target.attr("tag") == "barcode" || target.attr("tag") == "qrcode") {
        src = target.find("img").length > 0 ? target.find("img")[0].src : target.find("image").attr("xlink:href");
        unique = target.find("img").attr("unique");
      } else if (target.find("video").length > 0) {
        src = target.find("video").attr("original_url");
        unique = target.find("video").attr("unique");
      }
      setItemSelected(id);
      const index = $("#material_field .content ul li .preview.active").parent().index();

      //记录初始化时轮播框内容
      if (historyRecord.length == 0) {
        historyRecord.push({
          "cursor": 0,
          "index": index,//记录第几个轮播框
          "id": $("#material_field .content ul li .preview.active")[0].id,
          "html": $("#material_field .content ul li .preview.active")[0].outerHTML,
        });
      }

      if (elem) {
        //向操作历史列表中添加操作记录
        let batchCmd = new BatchCommand("Change image");
        let changes = {
          'xlink:href': elem.getAttribute('xlink:href'),
          'unique': elem.getAttribute('unique'),
        };

        elem.setAttribute("unique", unique);
        svgCanvas.setHref(elem, src);
        setRotation();
        if (null === $(this).click.caller) {//用户点击调用
          //向操作历史列表中添加操作记录
          batchCmd.addSubCommand(new ChangeElementCommand(elem, changes, index.toString()));
          svgCanvas.undoMgr.addCommandToHistory(batchCmd);



          let flag = true;
          for (i in historyRecord) {
            if (historyRecord[i].index == index && historyRecord[i].id) {
              flag = false;
            }
          }
          if (flag) {
            historyRecord.push({
              "cursor": svgCanvas.undoMgr.undoStackPointer,
              "index": index,//记录第几个轮播框
              "id": id,
              "html": $("#material_field .content ul li .preview.active")[0].outerHTML,
            });
          }
        }
      }
    }
  });
}

//素材轮播区域删除，默认选中第一个
function rotationFieldDelListener() {
  $("#material_field .content ul").on('click', "li>.del", function (e) {
    e.preventDefault();
    var target = $(e.target);
    if (target.hasClass("del")) {
      flag = true;
      var parentNode = target.parent()[0];
      var batchCmd = new BatchCommand('Del material');
      var parent = $("#material_field .content ul")[0];
      var nextSibling = parentNode.nextSibling;
      $(parentNode).remove();
      //向操作历史列表中添加操作记录
      batchCmd.addSubCommand(new RemoveElementCommand(parentNode, nextSibling, parent));
      svgCanvas.undoMgr.addCommandToHistory(batchCmd);

      $("#material_field .content ul li:first-child .preview").click();
      if ($("#material_field .content ul li").length == 1) {
        $("#material_field .content ul li .del").hide();
      } else {
        $("#material_field .content ul li .del").show();
      }
      setRotation();
    }
  });
}

//素材轮播区域添加，默认选中最后一个
function rotationFieldAddListener() {
  $("#material_field .content>img").click(function () {
    // console.log("添加")
    $("#material_field .content ul li .preview").removeClass("active");
    let selected = svgCanvas.getSelectedElems();
    var html = "";
    if (selected[0] == undefined) {//背景
      html = `<li>
              <span class="del">×</span>
              <div class="preview">
                <svg viewBox="0 0 ${WIDTH} ${HEIGHT}"><foreignObject width="${WIDTH}" height="${HEIGHT}"><image style="background:#262732"></image></foreignObject></svg>
              </div>
              <div class="mask"><span class="name" title=""></span></div>
              <div class="duration">
                <span>时长</span>
                <div class="number"></div>
                <span>秒</span>
              </div>
            </li>`;
    } else {
      const tag = selected[0].getAttribute("tag");
      if (tag == "material" || tag == "qrcode" || tag == "barcode") {
        html = `<li>
          <span class="del">×</span>
          <div class="preview">
            <svg viewBox="0 0 400 400" style="transform:">
              <foreignObject width="400" height="400" opacity="1" blur="0" orginal-transform="">
                <img src="">
              </foreignObject>
            </svg>
          </div>
          <div class="mask"><span class="name" title=""></span></div>
          <div class="duration">
            <span>时长</span>
            <div class="number"></div>
            <span>秒</span>
          </div>
        </li>`;
      } else if (tag == "webpage") {
        html = `<li>
          <span class="del">×</span>
          <div class="preview">
            <svg viewBox="0 0 400 400" style="transform:">
            <foreignObject width="400" height="400">
              <iframe width="100%" height="100%" allow="autoplay" frameborder="no" marginwidth="0" marginheight="0" scrolling="no" allowfullscreen=""></iframe>
            </foreignObject>
            </svg>
          </div>
          <div class="mask"><span class="name" title=""></span></div>
          <div class="duration">
            <span>时长</span>
            <div class="number"></div>
            <span>秒</span>
          </div>
        </li>`;
      } else {
        html = `<li>
          <span class="del">×</span>
          <div class="preview"></div>
          <div class="mask"><span class="name" title=""></span></div>
          <div class="duration">
            <span>时长</span>
            <div class="number"></div>
            <span>秒</span>
          </div>
        </li>`;
      }
    }
    $(this).prev().append(html);
    flag = true;
    $(this).prev().children().last().find(".preview").click();
    $("#material_field .content ul li").attr("draggable", true);
    initInputNumber($(this).prev().children().last().find(".number"));
    if ($("#material_field .content ul li").length == 1) {
      $("#material_field .content ul li .del").hide();
    } else {
      $("#material_field .content ul li .del").show();
    }
    setRotation();
    $('#material_field .content ul').scrollLeft($('#material_field .content ul')[0].scrollWidth);
    //向操作历史列表中添加操作记录
    var batchCmd = new BatchCommand('Add material');
    var elem = $($(this).prev())[0].lastChild;
    batchCmd.addSubCommand(new InsertElementCommand(elem));
    svgCanvas.undoMgr.addCommandToHistory(batchCmd);
  });

  $(document).on('dragend', "#material_field .content ul li", function (e) {
    setRotation();
  })
}

//二维码条形码输入时,生成按钮监听
function codeGenerateListener() {
  $("#code_panel .button").click(function () {
    let that = this;
    let value = $("#code_panel input[type='text']").val();
    if (value == "" || value == null) {
      $("#code_panel .error").attr('style', "display:block");
      return;
    }
    let height = 0;
    let width = 0;
    let tag = "";
    let img = "";
    let selected = svgCanvas.getSelectedElems();
    if (selected != "" && selected != null) {
      tag = selected[0].getAttribute("tag");
      img = $(selected[0]).find("image");
      width = $(selected)[0].width.animVal.value;
      height = $(selected)[0].height.animVal.value;
    } else {
      return;
    }
    $("#code_panel .error").hide();
    let foreColor = {};
    let backColor = {};
    let foreColorObj = colorFormatReverse($("#fill_color rect").attr("fill"));
    let backColorObj = colorFormatReverse($("#background_color rect").attr("fill"));
    if (foreColorObj != "none") {
      for (let i in foreColorObj) {
        foreColor.r = foreColorObj[0];
        foreColor.g = foreColorObj[1];
        foreColor.b = foreColorObj[2];
      }
    }
    if (backColorObj != "none") {
      for (let i in backColorObj) {
        backColor.r = backColorObj[0];
        backColor.g = backColorObj[1];
        backColor.b = backColorObj[2];
      }
    }

    var type = $(this).attr("type");
    let barcodeFormat = "";
    if (type == "qrcode") {
      barcodeFormat = "QR_CODE";
    } else {
      let flag = false;
      if (value.length == 7) {
        var reg = new RegExp(/^(\d{7})?$/);
        if (reg.exec(value)) {
          barcodeFormat = "EAN_8";
        } else {
          flag = true;
        }
      } else if (value.length == 12) {
        var reg = new RegExp(/^(\d{12})?$/);
        if (reg.exec(value)) {
          barcodeFormat = "EAN_13";
        } else {
          flag = true;

        }
      } else {
        flag = true;
      }

      if (flag) {
        $("#code_panel .error").html("条形码只能7位或者13位数字").css("display", "block");
        return;
      }
    }

    let data = {
      content: value,
      width: width <= height ? width : height,
      height: height >= width ? width : height,
      foreColor: foreColor,
      backColor: backColor,
      barcodeFormat: barcodeFormat,
    }
    $(that).html("生成中，请稍后");
    $.ajax({
      type: 'POST',
      contentType: CONTENT_TYPE,
      url: DOMAIN_BACK + API + 'qr-code/generate',
      dataType: 'json',
      data: JSON.stringify(data),
      beforeSend: function (request) {
        request.setRequestHeader("Authorization", localStorage.getItem("token"));
      },
      success: function (result, status, xhr) {
        const Authorization = xhr.getResponseHeader("authorization");
        requestListener(result.code, Authorization);
        if (result) {
          if (result.code == 200) {
            if (tag == "qrcode" || tag == "barcode") {
              let elem = img[0];
              let src = result.data.url;
              let id = result.data.id;
              html = '<svg viewBox="0 0 ' + width + ' ' + height + '"><foreignObject width="' + width + '" height="' + height + '"><image unique="' + id + '" src="' + src + '" /></foreignObject></svg>';
              //向操作历史列表中添加操作记录
              var batchCmd = new BatchCommand("Change img");
              var changes = {
                'unique': elem.getAttribute('unique'),
                'xlink:href': elem.getAttribute('xlink:href'),
              };
              batchCmd.addSubCommand(new ChangeElementCommand(elem, changes));
              svgCanvas.undoMgr.addCommandToHistory(batchCmd);
              elem.setAttribute("unique", id);
              svgCanvas.setHref(elem, src);
              $("#material_field .content ul li .preview.active").attr({ "id": id, "tag": type, "size": 21504 }).empty().append(html);
              setRotation();
            }
          } else if (result.code == 4501) {
            showModal("节目使用中不能编辑");
          }
        } else {
          showModal(result.message);
        }
        $(that).html("生成");
      },
      error: function (e) {
        if(e.responseJSON){
          var code = e.responseJSON.code;
          showModal(e.responseJSON.message);
          requestListener(code, "");
        }else{
          showModal("请求失败，请刷新重试");
        }
      }
    });
  });
}

//网页输入时,前往按钮监听
function setWebPageListener() {
  $("#webpage_panel .button").click(function () {
    var value = $("#webpage_panel input[type='text']").val();
    if (value == "" || value == null) {
      $("#webpage_panel .error").attr('style', "display:block");
      return;
    }
    $("#webpage_panel .error").hide();
    var selected = svgCanvas.getSelectedElems();
    if (selected != "" && selected != null) {
      var width = $(selected)[0].width.animVal.value;
      var height = $(selected)[0].height.animVal.value;
      var elem = $(selected[0]).find("iframe");
      elem.attr("src", value);
      var html = $(selected)[0].outerHTML;
      $("#material_field .content ul li .preview.active").attr({ "tag": "webpage" }).empty().append('<svg viewBox="0 0 ' + width + ' ' + height + '">' + html + '</svg>');
      setRotation();
    }
  });
}

//直播输入时,前往按钮监听
function setLiveListener() {
  $("#live_panel .button").click(function () {
    var value = $("#live_panel input[type='text']").val();
    if (value == "" || value == null) {
      $("#live_panel .error").attr('style', "display:block");
      return;
    }
    $("#live_panel .error").hide();
    var selected = svgCanvas.getSelectedElems();
    if (selected != "" && selected != null) {
      var width = $(selected)[0].width.animVal.value;
      var height = $(selected)[0].height.animVal.value;
      var fill = $(selected).attr("fill");
      var src =  $(selected).find('image').attr('xlink:href');
      var x = $(selected).find('image').attr('x');
      var y = $(selected).find('image').attr('y');
      let obj = $("#material_field .content ul li .preview.active svg");
      let transform = "";
      let orginal_transform = "";
      let opacity = 1;
      let blur = 0;
      if (obj.length > 0) {
        var element = obj.find("foreignObject");
        transform = obj[0].style.transform;
        orginal_transform = element.attr("orginal-transform");
        opacity = element.attr("opacity") == null ? 1 : element.attr("opacity");
        blur = element.attr("blur") == null ? 0 : element.attr("blur");
        // filter = element.attr("filter");
      }
      var html = `<svg viewBox="0 0 ${(width)} ${(height)}" style="transform:${(transform)};background:${(fill)};">
      <foreignObject width="${(width)}" height="${(height)}" 
        opacity="${(opacity)}" blur="${(blur)}" 
        orginal-transform="${(orginal_transform)}">
        <image src="${(src)}" unique="${(value)}" style="width:98px;height:98px;transform: translate(${x}px, ${y}px);"/>
      </foreignObject>
    </svg>`;
      $("#material_field .content ul li .preview.active").attr({ "tag": "live" }).empty().append(html);
      setRotation();
    }
  });
}

//预览事件监听
function previewListener() {
  $("#tool_preview").click(function () {
    if(!syncCheck()){
      $(".ant-modal-mask,.ant-modal-wrap[for='sync'] .ant-modal-body").html('<div>提示：设置同步的元素轮播时间段或播放内容不一致，请修改</div>');
      $(".ant-modal-mask,.ant-modal-wrap[for='sync']").show();
      return;
    }
    programConfig = createProgramConfig("preview");
    let html = $("#svgcontent")[0].outerHTML;
    $("#preview_container .content .body").append(html);
    $("#preview_container .content").css("width", $("#svgcontent")[0].width.animVal.value);
    initPreviewList("PREVIEW");
    $("#preview_container").show();
    if ($("#preview_container foreignObject[tag='time'] .time").length > 0) { tick() }
  });
  previewClose();
}

//一键发布
function publishListener() {
  $("#tool_publish").click(function () {
    if(!syncCheck()){
      $(".ant-modal-mask,.ant-modal-wrap[for='sync'] .ant-modal-body").html('<div>提示：设置同步的元素轮播时间段或播放内容不一致，请修改</div>');
      $(".ant-modal-mask,.ant-modal-wrap[for='sync']").show();
      return;
    }
    saveProgram().then(res => {
      const programList = [];
      let duration = 0;
      for (i in rotationList) {
        let temp = rotationList[i].duration;
        if (temp != undefined) {
          if (temp > duration) {
            duration = temp;
          }
        }
      }
      const programItem = new Object();
      programItem["key"] = 0;
      programItem["seq"] = 0;
      programItem["id"] = parseInt(window.methodDraw.id);
      programItem["name"] = $("#template_name").html();
      programItem["totalTime"] = duration;
      programItem["previewImgUrl"] = res.data;
      const dimensions = window.methodDraw.curConfig.dimensions;
      programItem["resolution"] = dimensions[0] + "x" + dimensions[1];
      programList.push(programItem);

      const playConfig = [{
        "id": 0,
        "startTime": "08:00:00",
        "endTime": "20:00:00",
        "type": "day",
        programList: programList,
      }];

      const Now = new Date();
      Now.setTime(Now.getTime());
      const month = Now.getMonth() + 1;
      const day = Now.getDate();
      const date = Now.getFullYear() + "-" + (month >= 10 ? month.toString() : "0" + month) + "-" + (day >= 10 ? day.toString() : "0" + day);
      const planName = "Plan" + Now.getFullYear().toString()
        + (Now.getMonth() + 1).toString() +
        Now.getDate().toString() +
        Now.getHours().toString() +
        Now.getMinutes().toString() +
        Now.getSeconds().toString();
      const planObj = {
        flag: "publish",
        describe: "",
        startDatetime: date + " 00:00:00",
        endDatetime: date + " 23:59:59",
        name: planName,
        playConfig: JSON.stringify(playConfig),
        playMode: 1,
        playStrategy: 0,
        programIds: window.methodDraw.id,
        publishType: 0,
        publishWay: 0,
      }
      const obj = {
        state: planObj,
      };
      window.parent.postMessage(JSON.stringify({ data: obj }), "*");
    }).catch(err => {
      console.log(err)
      $(".loading").hide();
      showModal("请求失败，请刷新重试");
    });
  });
}

//跳转到节目列表
function toProgramList() {
  window.parent.location.href = DOMAIN_BACK + '/program/list';
}

//退出编辑事件监听
function editOutListener() {
  $(".ant-modal-wrap[for='edit_out'] .ant-btn-default").click(function(){
    $(".ant-modal-mask,.ant-modal-wrap[for='edit_out']").hide();
    $(".pageLoading").show();
    $(".pageLoading .ant-spin-text").html("<span>退出中...</span>");
    const planObj = {
      planUpdate: false,
    }
    const obj = {
      state: planObj,
    };
    window.parent.postMessage(JSON.stringify({ data: obj }), "*");
    toProgramList();
  });
  $(".ant-modal-wrap[for='edit_out'] .ant-btn-primary").click(function(){
    $(".ant-modal-mask,.ant-modal-wrap[for='edit_out']").hide();
    $("#save").click();
  });
  
  $("#edit_out").click(function () {
    $(".ant-modal-mask,.ant-modal-wrap[for='edit_out']").show();
  });
}

// //读取js文件
function readTextFile(file) {
  let str = "";
  let rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.setRequestHeader("Cache-Control", "no-cache");
  rawFile.onreadystatechange = function () {
    if (rawFile.readyState === 4) {
      if (rawFile.status === 200 || rawFile.status == 0) {
        str = rawFile.responseText;
      }
    }
  }
  rawFile.send(null);
  return str;
}

//容量单位转换(kb,mb,gb,tb)
function bytesToSize(bytes) {
  if (bytes === 0) return '0 B';
  let k = 1024,
    sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    i = Math.floor(Math.log(bytes) / Math.log(k));

  return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}

var clearFlag = 0;
var count = 1;//设置3秒后自动消失

var autoClose = function () {
  if (count > 0) {
    count--;
  } else if (count <= 0) {
    window.clearInterval(clearFlag);
    $(".ant-message").fadeOut("slow");
    count = 1;
  }
}

var showModal = function (message) {
  $(".ant-message .text").html(message);
  $(".ant-message").fadeIn("slow");
  clearFlag = self.setInterval("autoClose()", 1000);//每过一秒调用一次autoClose方法
}

//新建监听
function createListener() {
  $("#create").click(function () {

  })
}

// 加载 image
function loadImage(url) {
  return new Promise(function (resolve, reject) {
    var image = new Image();
    image.crossOrigin = 'anonymous';
    image.onload = function () {
      resolve(this);
    };
    image.onerror = function (err) {
      reject(err);
    };
    image.src = url;
  });
}

function screenShot() {
  return new Promise(function (resolve, reject) {
    var svg = document.getElementById('svgcontent');
    var width = svg.getAttribute("width");
    var height = svg.getAttribute("height");
    var canvasBackground = document.getElementById('canvasBackground');
    var fill = $(canvasBackground).find("rect").attr("fill");
    var rotate = 0;
    $(canvasBackground).find("rect").attr({ "stroke": "none", "fill": $("#canvas_background").attr("fill") });
    var blobData = (new XMLSerializer()).serializeToString(canvasBackground);
    var children = svg.querySelectorAll('image,textarea,div.time,iframe');
    children = Array.prototype.slice.call(children);

    loadImage("data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(blobData)))).then(function (img) {
      $(canvasBackground).attr("fill", fill);
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext('2d');
      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(img, 0, 0);
      children.reduce(function (sequence, child) {
        return sequence.then(function () {
          var dX = 0, dY = 0, dW = 0, dH = 0, bit = 0;
          var tagName = child.tagName;
          if (tagName == "image") {
            var svgImg = child;
            var url = svgImg.getAttribute('xlink:href');
            return loadImage(url).then(function (sImg) {
              if (svgImg.getAttribute('id') == "bgImage") {
                bit = height / sImg.height;
                dX = (width - sImg.width * bit) / 2;
                dY = 0;
                dW = sImg.width * bit;
                dH = sImg.height * bit;
              } else {
                var imgW = sImg.naturalWidth;
                var imgH = sImg.naturalHeight;
                var parent = $(svgImg).parents("foreignObject:first")[0];
                bit = height / HEIGHT;
                dX = parent.getAttribute('x') * bit;//横坐标
                dY = parent.getAttribute('y') * bit;//纵坐标
                dW = width * parent.getAttribute('width') / WIDTH;//容器宽度
                dH = height * parent.getAttribute('height') / HEIGHT;//容器高度
                //计算图片的大小和位置
                if($(svgImg).parent().attr('tag') == 'live'){
                  var transform = parent.getAttribute('transform');
                  if (transform && transform.indexOf('rotate(') > -1) {
                    ctx.save();
                    rotate = transform.split("rotate(")[1].split(" ")[0];
                    var rectCenterPoint = { x: dX + dW / 2, y: dY + dH / 2 }; // 矩形中心点
                    ctx.translate(rectCenterPoint.x, rectCenterPoint.y);
                    ctx.rotate(rotate * Math.PI / 180);
                    ctx.translate(-rectCenterPoint.x, -rectCenterPoint.y);
                  }
                  ctx.fillStyle = '#2d8cf0';
                  ctx.fillRect(dX, dY, dW, dH);
                  dX = dX + (dW - 98) / 2;
                  dY = dY + (dH - 98) / 2;
                  dW = dH = 98;
                }else{
                  if (imgW / imgH < dW / dH) {
                    //按照foreignObject设置高
                    dX = dX + (dW - imgW * dH / imgH) / 2;
                    dW = imgW * dH / imgH;
                  } else if (imgW / imgH > dW / dH) {
                    //按照foreignObject设置宽
                    dY = dY + (dH - imgH * dW / imgW) / 2;
                    dH = imgH * dW / imgW;
                  }
                  if (parent ) {
                    var transform = parent.getAttribute('transform');
                    if (transform && transform.indexOf('rotate(') > -1) {
                      ctx.save();
                      rotate = transform.split("rotate(")[1].split(" ")[0];
                      var rectCenterPoint = { x: dX + dW / 2, y: dY + dH / 2 }; // 矩形中心点
                      ctx.translate(rectCenterPoint.x, rectCenterPoint.y);
                      ctx.rotate(rotate * Math.PI / 180);
                      ctx.translate(-rectCenterPoint.x, -rectCenterPoint.y);
                    }
                  }
                }
              }
              
              ctx.drawImage(sImg, dX, dY, dW, dH);
              ctx.restore();
            }, function (err) {
              //showModal(err);
            });
          } else if (tagName == "TEXTAREA" || $(child).hasClass('time')) {
            return loadImage(canvas.toDataURL()).then(function (sImg) {
              bit = height / HEIGHT;
              var parent = $(child).parents("foreignObject:first")[0];
              dX = parent.getAttribute('x') * bit;//横坐标
              dY = parent.getAttribute('y') * bit;//纵坐标
              dW = width * parent.getAttribute('width') / WIDTH;//容器宽度
              dH = height * parent.getAttribute('height') / HEIGHT;//容器高度

              var transform = parent.getAttribute('transform');
              if (transform && transform.indexOf('rotate(') > -1) {
                ctx.save();
                rotate = transform.split("rotate(")[1].split(" ")[0];
                var rectCenterPoint = { x: dX + dW / 2, y: dY + dH / 2 }; // 矩形中心点
                ctx.translate(rectCenterPoint.x, rectCenterPoint.y);
                ctx.rotate(rotate * Math.PI / 180);
                ctx.translate(-rectCenterPoint.x, -rectCenterPoint.y);
              }

              var fontSize = child.style.fontSize;
              var lineHeight = child.style.lineHeight;
              var fontFamily = child.style.fontFamily;
              var fontWeight = child.style.fontWeight;
              var fontStyle = child.style.fontStyle;
              var textDecoration = child.style.textDecoration;
              var color = child.style.color;
              var background = child.style.background;
              var text = "";
              if (tagName == "TEXTAREA") {
                text = child.value;
              } else {
                text = $(child).html();
              }
              ctx.fillStyle = background;
              ctx.fillRect(dX, dY, dW, dH);
              ctx.font = `${fontStyle} ${fontWeight} ${fontSize}/${fontSize.split('px')[0] * lineHeight}px ${fontFamily}`;
              ctx.fillStyle = color;
              ctx.textBaseline = "middle";
              ctx.fillText(text, dX, dY + dH / 2, dW);
              ctx.restore();
            });
          } else if (tagName == "IFRAME") {
            showModal("iframe暂不支持截屏");
          }
        }, function (err) {
          console.log(err);
        });
      },
        Promise.resolve()).then(function () {
          // console.log("绘制完成")
          resolve(canvas.toDataURL("image/jpeg"));
        });

    }, function (err) {
      console.log(err);
      reject(err);
    });
  });
}

function nameFormat(str) {
  const fileName = str.lastIndexOf(".");//获取到文件名开始到最后一个“.”的长度。
  const fileNameLength = str.length;//获取到文件名长度
  const fileFormat = str.substring(fileName + 1, fileNameLength);//截取后缀名
  return fileFormat;
}

function createLink(filename) {
  let link = "";
  const fileFormat = nameFormat(filename);
  if (fileFormat == "mp4") {

    const index = filename.lastIndexOf(".")
    const name = filename.substring(0, index);//截取后缀名
    link = `<link rel="prefetch" href="./${filename}" as="video" type="video/${nameFormat(filename)}"><link rel="prefetch" href="./${name}.jpg">`;
  } else {
    link = `<link rel="prefetch" href="./${filename}">`;
  }
  return link;
}

let createVideoLinkHtml = "";
function urlToId() {
  //轮播内容转换
  var fileList = [];
  const rotationList1 = JSON.parse(JSON.stringify(rotationList));
  for (var k in rotationList1) {
    const item1 = rotationList1[k];
    const html = item1.html;
    var tempHtml = "";
    if (html) {
      for (let i = 0; i < $(html).length; i++) {
        const item = $(html)[i];
        if ($(item).find("video,img").length > 0) {
          $(item).find("video,img").each(function () {
            const it = this;
            const src = it.getAttribute("src");
            it.setAttribute("online_src", src);
            if (src) {
              const unique = it.getAttribute("unique");
              const name = unique + '.' + nameFormat(src);
              it.setAttribute("online_src", src);
              fileList.push(name);
              if (it.tagName == "VIDEO") {
                it.setAttribute("src", "./" + name);
                it.setAttribute("poster", "./" + name.replace("." + nameFormat(src), ".jpg"));
                it.setAttribute("type", 'video/' + nameFormat(src));
                it.setAttribute("muted", '');
                it.setAttribute("preload", 'none');
                // it.removeAttribute("original_url");
                if (item1.id == "bgImage") {
                  it.setAttribute("play_src", "./" + name);
                  it.removeAttribute("src");
                }
                $(it).css("display", "none");
                var poster = it.getAttribute("poster");
                $(it).before(createPoster(poster));
              } else {
                it.setAttribute("src", "./" + name);
              }
            }
          });
        }
        tempHtml += item.outerHTML;
      }
      rotationList1[k].html = tempHtml;
    }
  }
  if (fileList.length > 0) {
    fileList = Array.from(new Set(fileList));
    for (var i = 0; i < fileList.length; i++) {
      createVideoLinkHtml += createLink(fileList[i]);
    }
  }
  return rotationList1;
}

function createProgramConfig(str) {
  let programJson = {};
  let programElements = [];
  for (i in rotationList) {
    //生成节目配置文件
    var elementConfig = {};
    var tag = rotationList[i].tag;
    if (tag == 'config') {
      programJson.width = rotationList[i].width;
      programJson.height = rotationList[i].height;
      continue;
    }
    var id = rotationList[i].id;
    var sync = rotationList[i].sync;
    var preserveAspectRatio = rotationList[i].preserveAspectRatio;
    elementConfig.id = id;
    elementConfig.tag = tag;
    //2.0.8 json配置文件添加x,y属性
    if(playModel == "android"){
      elementConfig.x =  $("#"+id).attr("x");
      elementConfig.y = $("#"+id).attr("y");
    }
    if (tag == 'material') {
      elementConfig.sync = sync ? true : false;
    }
    elementConfig.online = true;
    var array = [];
    var elementHtml = rotationList[i].html;
    if (elementHtml) {
      for (var j = 0; j < $(elementHtml).length; j++) {
        var unique = "", fileName = "", src = "";
        var item = $(elementHtml)[j];
        var config = {};
        config.durant = parseInt($(item).find(".num-input").val());
        config.width = $(item).find("foreignObject").attr("width");
        config.height = $(item).find("foreignObject").attr("height");
        var opacity = $(item).find("foreignObject").attr("opacity");
        config.opacity = opacity ? opacity : 1;
        if (tag == 'background' || tag == 'material' || tag == 'qrcode' || tag == 'barcode') {
          var targetElement = $(item).find("video,img")[0];
          if (targetElement) {
            src = targetElement.getAttribute("src");
            if (src) {
              unique = targetElement.getAttribute("unique");
              if (str == "publish") {
                fileName = unique + '.' + nameFormat(src);
              }
            }
            config.tagName = targetElement.tagName;
          }
          config.background = targetElement.style.background;
          config.unique = unique;
          config.src = (str == 'preview') ? src : fileName;
          config.online_src = src;
          
          config.transform = $(item).find("foreignObject").attr("orginal-transform");
          var original_url = $(item).find("foreignObject video").attr("original_url");
          if (original_url) {
            config.original_url = original_url;
            config.poster = (str == 'preview') ? original_url : `${unique}.jpg`;
          }
          config.preserveAspectRatio = preserveAspectRatio;
        } else if (tag == 'textarea') {
          var targetElement = $(item).find("textarea")[0];
          if (!targetElement) {
            continue;
          }
          config.value = targetElement.value;
          config.fontSize = targetElement.style.fontSize;
          config.fontFamily = targetElement.style.fontFamily;
          config.fontWeight = targetElement.style.fontWeight;
          config.fontStyle = targetElement.style.fontStyle;
          config.textDecoration = targetElement.style.textDecoration;
          config.transform = $(item).find("foreignObject").attr("transform");
          config.fill = $(item).find("foreignObject").attr("fill");
          config.strokeWidth = $(item).find("foreignObject").attr("stroke-width");
          config.strokeDasharray = $(item).find("foreignObject").attr("stroke-dasharray");
          config.lineHeight = targetElement.style.lineHeight;
          config.color = targetElement.style.color;
          config.background = targetElement.style.background ? targetElement.style.background : 'transparent';
        } else if (tag == 'webpage') {
          var targetElement = $(item).find("iframe")[0];
          if(targetElement){
            var src = targetElement.src;
            config.src = targetElement.src;
            config.transform = $(item).find("foreignObject").attr("orginal-transform");
          }
        }else if (tag == 'live') {
          var targetElement = $(item).find("img")[0];
          if(targetElement){
            config.transform = $(item).find("foreignObject").attr("orginal-transform");
            config.src = $(item).find("foreignObject img").attr("unique");
          }
        } else if (tag == 'time') {
          var targetElement = $("foreignObject[tag='time'] .time")[0];
          config.fontSize = targetElement.style.fontSize;
          config.fontFamily = targetElement.style.fontFamily;
          config.fontWeight = targetElement.style.fontWeight;
          config.fontStyle = targetElement.style.fontStyle;
          config.textDecoration = targetElement.style.textDecoration;
          config.transform = $("foreignObject[tag='time']").attr("transform");
          config.fill = $("foreignObject[tag='time']").attr("fill");
          config.strokeWidth = $("foreignObject[tag='time']").attr("stroke-width");
          config.strokeDasharray = $("foreignObject[tag='time']").attr("stroke-dasharray");
          config.lineHeight = targetElement.style.lineHeight;
          config.color = targetElement.style.color;
          config.background = targetElement.style.background ? targetElement.style.background : 'transparent';
        }

        function randomString(e) {
          e = e || 32;
          var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
            a = t.length,
            n = "";
          for (i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
          return n
        }

        config.dataId = randomString(32);
        config.online = true;
        array.push(config);
      }
    }
    elementConfig.elements = array;
    programElements.push(elementConfig);
  }
  programJson.elements = programElements;
  // console.log(JSON.stringify(programJson));
  return programJson;
}

//保存操作
function saveProgram() {
  var elementInfo = "";
  return new Promise(function (resolve, reject) {
    $(".pageLoading").show();
    $("#material_field .content ul li:first>.preview").click();
    $(".pageLoading .ant-spin-text").html("<span>节目预览图生成中...</span>");
    screenShot().then(function (blobUrl) {
      $(".pageLoading .ant-spin-text").html("<span>节目预览图生成完成</span>");
      // console.log(blobUrl)
      $(".pageLoading .ant-spin-text").append("<span id='text2'>节目配置文件生成中...</span>");
      programConfig = createProgramConfig("preview");
      elementInfo = JSON.stringify(createProgramConfig('publish'));
      let html = `<!doctype html>
      <html lang="zh">
      <head>
      <meta charset="utf-8"/>
      <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"/>
      <meta name="theme-color" content="#000000"/>
      <title>智慧媒体管理系统2.0.8</title>
      <style>
      body{margin:0}.body{position:absolute;width:100%;height:100%;left:0;top:0;z-index: 0;} .previewContainer .body{position:relative;}#bgImage{position:absolute;z-index:1;top:0;left:0;width: 100%;height: 100%;pointer-events: none;}#bgImage:not([src]){opacity: 0;}.body foreignObject:not([tag="webpage"]),.body foreignObject textarea{border: none;pointer-events: none !important;position:relative;overflow:visible;}.body foreignObject textarea{width:100%;height:100%;resize:none;border:none;overflow:hidden;display:flex;z-index:5;}.body foreignObject img,.body foreignObject video{position:relative;width:100%;height:100%;object-fit:contain;pointer-events: none;display:flex;z-index:5;}.body foreignObject img.poster{position:absolute;width:100%;height:100%;top:0;left:0;z-index:2;}foreignObject[tag="time"] .time{display: flex;width: 100%;height:100%;justify-content: center;align-items: center;text-align: center;position: absolute;}.body foreignObject iframe{position:relative;display:flex;z-index:5;}img[src=""],img:not([src]){visibility:hidden}video:not([src]){display: none !important;}
      .body #svgcontent>g:first-child{position: absolute;z-index: 0;}
      .body #svgcontent>g:last-child{position: absolute;z-index: 3;}
      .body #svgcontent>g:last-child foreignObject img.poster{position: relative;}
      .topZindex{position: relative !important;}
      .body foreignObject canvas{position: relative;z-index:5}
      .body foreignObject img[preserveAspectRatio="none"], .body foreignObject video[preserveAspectRatio="none"]{object-fit: fill;}
      .body .error{position: absolute;top: 0;bottom: 0;left: 0;right: 0;background: #262732;color:#fffbe6;display: flex;align-items: center;justify-content: center;font-size: 7rem;}
      </style>
      <script>`+ readTextFile('../lib/jquery.min.js') + readTextFile('../src/html_browser.js?timestamp='+Date.parse(new Date())) +
        `var programConfig = ${JSON.stringify(programConfig)};</script>
      </head><body><div class="body">` + $("#svgcontent")[0].outerHTML + `</div>
      <script>
        // $("body image,body img").attr("xlink:href", "");
        var images = window.document.getElementsByClassName("body")[0].querySelectorAll("image,img");
        for(var i =0; i<images.length; i++){
          images[i].setAttribute("xlink:href","");
        }
        iframe = window.document.getElementsByClassName("body")[0].querySelectorAll("iframe");
        if(iframe>0){iframe_src = iframe[0].getAttribute("src");iframe[0].src ="";}
        var href = window.location.href;
        if(href.indexOf("http") == -1 || IS_ANDROID){
          initIMage();
        }else{
          initPreviewList('PREVIEW');
        }
      </script>
      </body></html>`;
      $(".pageLoading .ant-spin-text #text2").html("节目配置文件生成完成");
      let duration = 0; //节目时长，按照控件轮播算
      let playList = []; //节目资源列表id
      let sizeList = [];
      let width = rotationList[0].width;
      let height = rotationList[0].height;
      let name = $("#template_name").html();

      for (i in rotationList) {
        let temp = rotationList[i].duration;
        if (temp != undefined) {
          if (temp > duration) {
            duration = temp;
          }
        }
        let list = rotationList[i].playList;
        if (list != undefined && list.length > 0) {
          playList = playList.concat(list);
        }
        let sizes = rotationList[i].sizeList;
        if (sizes != undefined && sizes.length > 0) {
          sizeList = sizeList.concat(sizes);
        }
      }
      // console.log("节目分辨率：宽"+width+" 高 "+height);
      // console.log("节目时长："+duration)
      // return;
      //数组去重
      let newSet = new Set(playList);
      playList = Array.from(newSet).toString();
      // console.log("节目资源id列表：" + playList);
      // return;
      // console.log("节目资源大小列表："+sizeList);
      let sizeBytes = 0;
      if (sizeList.length > 0) {
        for (i in sizeList) {
          let sizeItem = parseInt(sizeList[i]);
          sizeBytes += sizeItem;
        }
      }
      // console.log("节目资源大小："+sizeBytes);
      // console.log(JSON.stringify(rotationList));
      // console.log(html);
      // console.log("模板名称："+ name);
      // console.log(STATUS);
      let data = "";
      let url = "program/add";
      let type = "POST";
      if (STATUS == "add") {
        data = {
          name: name,//节目名称
          resolutionHeight: height,//分辨率:高
          resolutionWidth: width,//分辨率:宽
          totalTime: duration,//总时长
          totalSize: sizeBytes,//总大小
          previewImgUrl: blobUrl,//预览图地址  测试
          deviceType: 'LCD',//设备类型  测试         
          editHtml: JSON.stringify(rotationList),//录播json
          resourceIds: playList,//节目资源id列表
          publishHtml: html,//html页面
          elementInfo: elementInfo, //program.json
        }
      } else {
        data = {
          id: window.methodDraw.id,//节目id
          totalTime: duration,//总时长
          totalSize: sizeBytes,//总大小
          previewImgUrl: blobUrl,//预览图地址  测试        
          editHtml: JSON.stringify(rotationList),//录播json
          resourceIds: playList,//节目资源id列表
          publishHtml: html,//html页面
          elementInfo: elementInfo, //program.json
        }
        url = "program/designHtml";
        type = "PUT";
      }
      $(".pageLoading .ant-spin-text").append("<span id='text3'>节目保存中...</span>");
      $.ajax({
        type: type,
        contentType: CONTENT_TYPE,
        url: DOMAIN_BACK + API + url,
        dataType: 'json',
        data: JSON.stringify(data),
        beforeSend: function (request) {
          request.setRequestHeader("Authorization", localStorage.getItem("token"));
        },
        success: function (result, status, xhr) {
          const Authorization = xhr.getResponseHeader("authorization");
          requestListener(result.code, Authorization);
          if (result) {
            if (result.code == 200) {
              $(".pageLoading .ant-spin-text #text3").html("节目保存成功，<br/>正在跳转请稍后...");
              resolve(result)
            } else {
              $(".pageLoading .ant-spin-text #text3").html("节目保存失败");
              resolve(result);
            }
          } else {
            $(".pageLoading .ant-spin-text #text3").html("节目保存失败");
            resolve(result);
          }
        },
        error: function (e) {
          console.log(e.responseJSON);
          // showModal("请求失败，" + e.responseJSON);
          if(e.responseJSON){
            var code = e.responseJSON.code;
            e.message = e.responseJSON.message;
            // showModal(e.responseJSON.message);
            requestListener(code, "");
          }else{
            e.message = "请求失败，请刷新重试";
          }
          reject(e);
        }
      });
    });
  })
}
//同步元素配置比较
function syncCheck() {
  var result = true;
  var array = [];
  rotationList.map((rotate)=>{
    if(rotate.tag == 'material' && (rotate.sync || rotate.sync == 'true')){
      var elementHtml = rotate.html;
      if (elementHtml) {
        var arr = [];
        for (var j = 0; j < $(elementHtml).length; j++) {
          var item = $(elementHtml)[j];
          var durant = parseInt($(item).find(".num-input").val());
          arr.push(durant)
        }
        rotate.playList.map(item=>{
          if(item){
            arr.push(item);
          }else{
            result = false;
          }
        })
        array.push(arr.toString());
      }else{
        result = false;
      }
    }
  });
  if(result && array.length>0){
    for(var i in array){
      if(i>0){
        if(array[i] != array[i-1]){
          result = false;
        }
      }
    }
  }
  return result;
}
//保存事件监听
function saveListener() {
  $("#save").click(function () {
    if(!syncCheck()){
      $(".ant-modal-mask,.ant-modal-wrap[for='sync'] .ant-modal-body").html('<div>提示：设置同步的元素轮播时间段或播放内容不一致，请修改</div>');
      $(".ant-modal-mask,.ant-modal-wrap[for='sync']").show();
      return;
    }
    saveProgram().then(res => {
      if (res.code === 200) {
        const planObj = {
          planUpdate: true,
        }
        const obj = {
          state: planObj,
        };
        window.parent.postMessage(JSON.stringify({ data: obj }), "*");
        toProgramList();
      } else {
        showModal(res.message);
        $(".loading").hide();
      }

    }).catch(err => {
      showModal(err.message);
      $(".loading").hide();
    });
  });
}

function syncListener() {
  $("#conMenu #syncTag input").on('click', function () {
    var elems = svgCanvas.getSelectedElems();
    if (elems.length == 1 && elems[0]) {
      var elem = elems[0];
      if (this.checked) {
        elem.setAttribute("sync", true);
        var id = $(elem).attr('id');
        for (var i = 0; i < rotationList.length; i++) {
          if (rotationList[i].id == id) {
            rotationList[i].sync = true;
          }
        }
        if (alertStatus) {
          $(".ant-modal-mask,.ant-modal-wrap[for='sync'] .ant-modal-body").html('<div>提示：设置同步的元素轮播时间段和播放内容将保持一致，同步视频建议最大为3个，以免影响性能</div>');
          $(".ant-modal-mask,.ant-modal-wrap[for='sync']").show();
        }
      } else {
        elem.removeAttribute("sync");
        var id = $(elem).attr('id');
        for (var i = 0; i < rotationList.length; i++) {
          if (rotationList[i].id == id) {
            delete rotationList[i].sync;
          }
        }
      }
    }
  });
  $("#conMenu #preserveAspectRatio input").on('click', function () {
    var elems = svgCanvas.getSelectedElems();
    if (elems.length == 0) {//背景
      elems = $("#bgImage").parent();
    }
    if (elems.length == 1 && elems[0]) {
      var elem = elems[0];
      if (this.checked) {
        $(elem).find("image")[0].setAttribute("preserveAspectRatio", "none");
        $("#material_field .content ul li .preview").find("img,video").attr("preserveAspectRatio", 'none');
        var id = $(elem).attr('id');
        for (var i = 0; i < rotationList.length; i++) {
          if (rotationList[i].id == id) {
            rotationList[i].preserveAspectRatio = 'none';
          }
        }
      } else {
        $(elem).find("image")[0].removeAttribute("preserveAspectRatio");
        $("#material_field .content ul li .preview").find("img,video").removeAttr("preserveAspectRatio");
        var id = $(elem).attr('id');
        for (var i = 0; i < rotationList.length; i++) {
          if (rotationList[i].id == id) {
            rotationList[i].preserveAspectRatio = null;
          }
        }
      }
      setRotation();
    }
  });
}

function tipListener() {
  $(".draginput input, #tool_textarea_bold,#tool_textarea_italic,#tool_textarea_underline").hover(function () {
    var top = $(this).offset().top + 'px';
    var left = $(this).offset().left - 100 + 'px';
    var text = $(this).data("title")
    $(".ant-tooltip .ant-tooltip-inner span").html(text);
    $(".ant-tooltip").css({ "top": top, "left": left }).show();
  }, function () {
    $(".ant-tooltip .ant-tooltip-inner span").empty();
    $(".ant-tooltip").hide();
  })
}
function dialogListener(){
  $(".ant-modal-wrap .ant-modal .ant-modal-close").on('click',function(){
    $(".ant-modal-mask,.ant-modal-wrap").hide();
  });
}

function elementResizeAble(resizeAble){
  if(resizeAble && !JSON.parse(resizeAble))
    return false;
  else 
    return true;
}

function elementMoveAble(moveAble){
  if(moveAble && !JSON.parse(moveAble))
    return false;
  else 
    return true;
}
function initLayout(){
  var layout = rotationList[0].layout;
  if(!layout){//原生--新建
    rotationList[0].layout = WIDTH>HEIGHT?'H1':'V1';
    for(var i=0;i<rotationList.length;i++){
      if(rotationList[i].id == "bgImage"){
        rotationList.splice(i, 1);
      }
    }
    $("#tools_left .layout.horizontal").is(":visible")?
    $("#tools_left .layout.horizontal>svg:first").attr("class","active"):
    $("#tools_left .layout.vertical>svg:first").attr("class","active");
    setLayout(rotationList[0].layout);
  }else{//原生--编辑
    $("#tools_left .layout>svg[layout='"+layout+"']").attr('class','active');
  }
}

function appendLayout(point){
  var html = $($("#svgcontent>g")[1]).html();
  var newHTML = html + `<foreignObject fill="#fff" stroke="#000" stroke-width="0" tag="material" 
  x="${point.x}" y="${point.y}" id="svg_${point.i}" width="${point.width}" height="${point.height}" type="layout" resizeable=false moveable=false >
  <svg viewBox="0 0 ${point.width} ${point.height}" tag="material">
    <rect x="0" y="0" width="${point.width}" height="${point.height}" fill="transparent"></rect>
    <image xlink:href="" width="${point.width}" height="${point.height}" x="0" y="0" transform="rotate(0, 200, 200)" opacity="1"></image>
  </svg></foreignObject>`;
  $($("#svgcontent>g")[1]).html(newHTML);
}

function setLayout(layout){
  var length = 0;
  var pointArray = [];
  switch(layout){
    case 'H1':
    case 'V1':
      length = 1;
      var w = WIDTH/length;
      for(var i = 0;i<length;i++){
        var point = Object();
        point.x = i*w;
        point.y = 0;
        point.width = w;
        point.height = HEIGHT;
        point.i = i+1;
        pointArray.push(point);
        appendLayout(point);
      }
    break;
    case 'V4':
      length = 3;
      var h = HEIGHT/length;
      for(var i = 0;i<length;i++){
        var point = Object();
        point.x = 0;
        point.y = i*h;
        point.width = WIDTH;
        point.height = h;
        point.i = i+1;
        pointArray.push(point);
        appendLayout(point);
      }
    break;
    case 'H2':
      length = 3;
      pointArray.push({x:0,y:0,width:WIDTH/2,height:HEIGHT,i:1});
      appendLayout(pointArray[0]);
      var h = HEIGHT/(length - 1);
      for(var i = 0;i<length-1;i++){
        var point = Object();
        point.x = WIDTH/2;
        point.y = i*h;
        point.width = WIDTH/2;
        point.height = h;
        point.i = i+2;
        pointArray.push(point);
        appendLayout(point);
      }
      break;
    case 'H3':
      length = 3;
      var h = HEIGHT/(length - 1);
      for(var i = 0;i<length-1;i++){
        var point = Object();
        point.x = 0;
        point.y = i*h;
        point.width = WIDTH/2;
        point.height = h;
        point.i = i+1;
        pointArray.push(point);
        appendLayout(point);
      }
      pointArray.push({x:WIDTH/2,y:0,width:WIDTH/2,height:HEIGHT,i:length});
      appendLayout(pointArray[length - 1]);
    break;
  case 'V3':
    length = 3;
    pointArray.push({x:0,y:0,width:WIDTH,height:HEIGHT/2,i:1});
    appendLayout(pointArray[0]);
    var w = WIDTH/(length - 1);
    for(var i = 0;i<length-1;i++){
      var point = Object();
      point.x = i*w;
      point.y = HEIGHT/2;
      point.width =w;
      point.height = HEIGHT/2;
      point.i = i+2;
      pointArray.push(point);
      appendLayout(point);
    }
    break;
  case 'V2':
    length = 3;
    var w = WIDTH/(length - 1);
    for(var i = 0;i<length-1;i++){
      var point = Object();
      point.x = i*w;
      point.y = 0;
      point.width =w;
      point.height = HEIGHT/2;
      point.i = i+1;
      pointArray.push(point);
      appendLayout(point);
    }
    pointArray.push({x:0,y:HEIGHT/2,width:WIDTH,height:HEIGHT/2,i:length});
    appendLayout(pointArray[length - 1]);
    break;
  case 'H4':
  case 'V5':
    length = 4;
    var w = WIDTH/(length/2);
    for(var i = 0;i<length;i++){
      var point = Object();
      if(i<2){
        point.x = i*w;
        point.y = 0;
      }else{
        var j = i - 2;
        point.x = j*w;
        point.y = HEIGHT/2;
      }
      point.width =w;
      point.height = HEIGHT/2;
      point.i = i+1;
      pointArray.push(point);
      appendLayout(point);
    }
    break;
    default:
    break;
  }
}

function layoutListener(){
  let layout = '';
  $(".ant-modal-wrap[for='layout'] .ant-btn-default").click(function(){
    $(".ant-modal-mask,.ant-modal-wrap[for='layout']").hide();
  });

  $(".ant-modal-wrap[for='layout'] .ant-btn-primary").click(function(){
    $(".ant-modal-mask,.ant-modal-wrap[for='layout']").hide();
    $("#tools_left .layout>svg").removeAttr('class');
    $("#tools_left .layout>svg[layout='"+layout+"']").attr('class','active');
    $('#workarea #svgcontent').find('g:eq(1)').empty();//清空画布
    rotationList[0].layout = layout;
    rotationList = [rotationList[0]];//清空轮播配置文件
    setLayout(layout);
    $("#svg_1").mousedown();
  });
  
  $("#tools_left .layout>svg").on('click', function () {
    if($(this).attr("class") == 'active') return;
    $("#conMenu").hide();
    $("#selectorGroup0").attr("display",'none');
    $(".ant-modal-mask,.ant-modal-wrap[for='layout']").show();
    layout = $(this).attr('layout');
  });
}

const STATUS = window.methodDraw.status;
const WIDTH = window.methodDraw.curConfig.dimensions[0];
const HEIGHT = window.methodDraw.curConfig.dimensions[1];
const playModel = window.methodDraw.playModel;
// const playModel = 'android';
let alertStatus = true;
window.onload = function () {
  window.addEventListener("message", function (event) {
    // 把父窗口发送过来的数据显示在子窗口中
    if (event && event.data && typeof(event.data) == 'string') {
      const data = JSON.parse(event.data).data;
      const token = data.token;
      // const idUrlMaps = data.idUrlMaps;
      DOMAIN_BACK = data.domain;
      window.localStorage.setItem("token", token);
      // localStorage.setItem("idUrlMaps",JSON.stringify(idUrlMaps));
      $("#template_name").html(window.methodDraw.name);//初始化名称
      $("#tools_left .layout").hide();
      if(playModel == "android"){
        $("#tools_left .layoutLabel").show();
        if(WIDTH>HEIGHT){//横屏
          $("#tools_left .layout.horizontal").show();
        }else{ 
          $("#tools_left .layout.vertical").show();
        }
        //2.0.8控制字体下拉框
        $("#textarea_font_family_dropdown option").each(function(){
          $(this).hasClass('android')?$(this).show():$(this).hide();
        })
      }else{
        $("#tool_live").remove();
        $("#tools_left .layoutLabel,#tools_left .layout").remove();
      }
      if (STATUS != "add") {//编辑节目
        initCanvas();
        
      } else {
        $(".loading").hide();
      }
      
      initCanvasSize();
      let resizeTimer = null;
      //调整浏览器大小，重新设置画布尺寸
      $(window).bind('resize', function () {
        if (resizeTimer) clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function () {
          initCanvasSize();
        }, 500);
      });
      setTooltip();
      previewListener();
      publishListener();
      editOutListener();
      saveListener();
      syncListener();
      // shapeListener();
      textAreaInputListener();
      initMenuListener();
      //初始化数字输入框
      initInputNumber($("#tools_left .reference_line .x,#tools_left .reference_line .y"), 0, 100); //参考线
      if (STATUS == 'add') {//建节目
        initInputNumber($("#material_field .content ul li .duration .number")); //轮播框
      }
      lineSelectListener();
      addLineListener();
      tabListener();
      materialChooseListener();
      rotationFieldListener();
      rotationFieldSelectListener();
      rotationFieldDelListener();
      rotationFieldAddListener();
      codeGenerateListener();
      setWebPageListener();
      setLiveListener();
      searchListener();
      svgCanvas.undoMgr.resetUndoStack();//清空history
      tipListener();
      dialogListener();
      if(playModel == "android"){
        layoutListener();
      }
    }
  }, false);
}